<template>
  <div class="unified-practice">
    <div class="practice-content">
      <!-- 练习设置已移除，直接显示题目 -->
      
      <div class="question-area" v-if="currentQuestion">
        <div class="question-container">
          <el-card class="question-card">
            <template #header>
              <div class="card-header">
                <el-button 
                  type="primary" 
                  @click="returnToSettings" 
                  class="return-btn"
                  size="small"
                  :icon="ArrowLeft"
                  title="返回"
                ></el-button>
                <div class="question-info">
                  <span class="question-number">第 {{ currentIndex + 1 }} 题 / 共 {{ questions.length }} 题 【{{ getDisplayModuleName() }}】</span>
                </div>
                <div class="question-tags">
                  <el-tag type="info" style="margin-left: 10px;">
                    <span class="tag-content">{{ getTypeText(currentQuestion.type || 'single_choice') }}</span>
                  </el-tag>
                </div>
              </div>
            </template>
            
            <div class="question-content">
              <h3><span class="question-index">{{ currentIndex + 1 }}.</span> <span v-html="sanitizeHtml(currentQuestion.content)"></span></h3>
              
              <!-- 单选题 -->
              <div class="options" v-if="!currentQuestion.type || currentQuestion.type === 'single' || currentQuestion.type === 'single_choice'">
                <el-radio-group v-model="userAnswer" :disabled="practiceForm.mode === 'drill' && showAnswerForDrill">
                  <el-radio 
                    v-for="(option, index) in parseOptions(currentQuestion.options)" 
                    :key="index" 
                    :label="option.key"
                    class="option-item">
                    <div class="option-content">
                      <span class="option-key">{{ option.key }}</span>
                      <template v-if="isImageUrl(option.value)">
                        <img :src="option.value" alt="选项图片" class="option-image" />
                      </template>
                      <template v-else>
                        <span class="option-value" v-html="sanitizeOptionHtml(option.value)"></span>
                      </template>
                    </div>
                  </el-radio>
                </el-radio-group>
                
                <!-- 刷题模式下显示答案和解析 -->
                <div v-if="practiceForm.mode === 'drill' && showAnswerForDrill">
                  <!-- 刷题模式下显示上一页和下一页按钮 -->
                  <div class="question-actions" style="margin-top: 20px; margin-bottom: 20px;">
                    <el-button @click="previousQuestion" :disabled="currentIndex === 0" class="nav-button">
                      上一题
                    </el-button>
                    <el-button type="primary" @click="skipOrNextQuestionInDrillMode" v-if="currentIndex < questions.length - 1" class="nav-button">
                      下一题
                    </el-button>
                    <el-button type="success" @click="submitPractice" v-if="currentIndex === questions.length - 1" :loading="submitting" class="submit-button">
                      提交答案
                    </el-button>
                  </div>
                  
                  <div class="drill-answer-section">
                    <div class="answer-explanation">
                      <p><strong>正确答案：</strong><span class="correct-answer">{{ formatAnswer(currentQuestion.correctAnswer) }}</span></p>
                      <div v-if="currentQuestion.explanation || currentQuestion.analysis" class="explanation-content">
                        <strong>解析：</strong>
                        <div v-html="sanitizeHtml(currentQuestion.explanation || currentQuestion.analysis)"></div>
                      </div>
                    </div>
                    
                    <!-- AI答案和解析 -->
                    <div class="ai-answer-section" v-if="showAIAnswer">
                      <div class="ai-loading" v-if="aiLoading">
                        <el-icon class="is-loading"><Loading /></el-icon>
                        <span>AI正在生成答案解析...</span>
                      </div>
                      <div v-else>
                        <div class="ai-answer-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                          <strong>AI解析：</strong>
                          <el-button 
                            v-if="practiceForm.mode === 'drill' && aiAnswer && !aiLoading" 
                            type="success" 
                            size="small" 
                            @click="applyAIAnswerToDatabase"
                            class="apply-ai-btn"
                            :loading="applyingAI"
                          >
                            应该AI答案
                          </el-button>
                        </div>
                        <div class="ai-answer-content" v-if="aiAnswer">
                          <div v-html="sanitizeHtml(aiAnswer)" class="ai-content"></div>
                        </div>
                        <el-button 
                          v-if="!aiAnswer && !aiLoading && (currentQuestion.explanation || currentQuestion.analysis)" 
                          type="primary" 
                          size="small" 
                          @click="generateAIAnswer"
                          :loading="aiLoading"
                          class="generate-ai-btn"
                        >
                          获取AI解析
                        </el-button>
                        <div v-if="!aiAnswer && !aiLoading && !(currentQuestion.explanation || currentQuestion.analysis)">
                          <!-- 如果没有原有解析内容，自动加载AI解析 -->
                          <div class="ai-loading">
                            <el-icon class="is-loading"><Loading /></el-icon>
                            <span>AI正在生成答案解析...</span>
                          </div>
                        </div>

                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 多选题 -->
              <div class="options" v-if="currentQuestion.type === 'multiple' || currentQuestion.type === 'multiple_choice'">
                <el-checkbox-group v-model="userAnswer" :disabled="practiceForm.mode === 'drill' && showAnswerForDrill">
                  <el-checkbox 
                    v-for="(option, index) in parseOptions(currentQuestion.options)" 
                    :key="index" 
                    :label="option.key"
                    class="option-item">
                    <div class="option-content">
                      <span class="option-key">{{ option.key }}</span>
                      <template v-if="isImageUrl(option.value)">
                        <img :src="option.value" alt="选项图片" class="option-image" />
                      </template>
                      <template v-else>
                        <span class="option-value" v-html="sanitizeOptionHtml(option.value)"></span>
                      </template>
                    </div>
                  </el-checkbox>
                </el-checkbox-group>
                
                <!-- 刷题模式下显示答案和解析 -->
                <div v-if="practiceForm.mode === 'drill' && showAnswerForDrill">
                  <!-- 刷题模式下显示上一页和下一页按钮 -->
                  <div class="question-actions" style="margin-top: 20px; margin-bottom: 20px;">
                    <el-button @click="previousQuestion" :disabled="currentIndex === 0" class="nav-button">
                      上一题
                    </el-button>
                    <el-button type="primary" @click="skipOrNextQuestionInDrillMode" v-if="currentIndex < questions.length - 1" class="nav-button">
                      下一题
                    </el-button>
                    <el-button type="success" @click="submitPractice" v-if="currentIndex === questions.length - 1" :loading="submitting" class="submit-button">
                      提交答案
                    </el-button>
                  </div>
                  
                  <div class="drill-answer-section">
                    <div class="answer-explanation">
                      <p><strong>正确答案：</strong><span class="correct-answer">{{ formatAnswer(currentQuestion.correctAnswer) }}</span></p>
                      <div v-if="currentQuestion.explanation || currentQuestion.analysis" class="explanation-content">
                        <strong>解析：</strong>
                        <div v-html="sanitizeHtml(currentQuestion.explanation || currentQuestion.analysis)"></div>
                      </div>
                    </div>
                    
                    <!-- AI答案和解析 -->
                    <div class="ai-answer-section" v-if="showAIAnswer">
                      <div class="ai-loading" v-if="aiLoading">
                        <el-icon class="is-loading"><Loading /></el-icon>
                        <span>AI正在生成答案解析...</span>
                      </div>
                      <div v-else>
                        <div class="ai-answer-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                          <strong>AI解析：</strong>
                          <el-button 
                            v-if="practiceForm.mode === 'drill' && aiAnswer && !aiLoading" 
                            type="success" 
                            size="small" 
                            @click="applyAIAnswerToDatabase"
                            class="apply-ai-btn"
                            :loading="applyingAI"
                          >
                            应该AI答案
                          </el-button>
                        </div>
                        <div class="ai-answer-content" v-if="aiAnswer">
                          <div v-html="sanitizeHtml(aiAnswer)" class="ai-content"></div>
                        </div>
                        <el-button 
                          v-if="!aiAnswer && !aiLoading && (currentQuestion.explanation || currentQuestion.analysis)" 
                          type="primary" 
                          size="small" 
                          @click="generateAIAnswer"
                          :loading="aiLoading"
                          class="generate-ai-btn"
                        >
                          获取AI解析
                        </el-button>
                        <div v-if="!aiAnswer && !aiLoading && !(currentQuestion.explanation || currentQuestion.analysis)">
                          <!-- 如果没有原有解析内容，自动加载AI解析 -->
                          <div class="ai-loading">
                            <el-icon class="is-loading"><Loading /></el-icon>
                            <span>AI正在生成答案解析...</span>
                          </div>
                        </div>

                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 判断题 -->
              <div class="options" v-if="currentQuestion.type === 'judge' || currentQuestion.type === 'true_false'">
                <el-radio-group v-model="userAnswer" :disabled="practiceForm.mode === 'drill' && showAnswerForDrill">
                  <el-radio label="true" class="option-item">
                    <div class="option-content">
                      <el-icon><Select /></el-icon> 正确
                    </div>
                  </el-radio>
                  <el-radio label="false" class="option-item">
                    <div class="option-content">
                      <el-icon><Close /></el-icon> 错误
                    </div>
                  </el-radio>
                </el-radio-group>
                
                <!-- 刷题模式下显示答案和解析 -->
                <div v-if="practiceForm.mode === 'drill' && showAnswerForDrill">
                  <!-- 刷题模式下显示上一页和下一页按钮 -->
                  <div class="question-actions" style="margin-top: 20px; margin-bottom: 20px;">
                    <el-button @click="previousQuestion" :disabled="currentIndex === 0" class="nav-button">
                      上一题
                    </el-button>
                    <el-button type="primary" @click="skipOrNextQuestionInDrillMode" v-if="currentIndex < questions.length - 1" class="nav-button">
                      下一题
                    </el-button>
                    <el-button type="success" @click="submitPractice" v-if="currentIndex === questions.length - 1" :loading="submitting" class="submit-button">
                      提交答案
                    </el-button>
                  </div>
                  
                  <div class="drill-answer-section">
                    <div class="answer-explanation">
                      <p><strong>正确答案：</strong><span class="correct-answer">{{ formatAnswer(currentQuestion.correctAnswer) }}</span></p>
                      <div v-if="currentQuestion.explanation || currentQuestion.analysis" class="explanation-content">
                        <strong>解析：</strong>
                        <div v-html="sanitizeHtml(currentQuestion.explanation || currentQuestion.analysis)"></div>
                      </div>
                    </div>
                    
                    <!-- AI答案和解析 -->
                    <div class="ai-answer-section" v-if="showAIAnswer">
                      <div class="ai-loading" v-if="aiLoading">
                        <el-icon class="is-loading"><Loading /></el-icon>
                        <span>AI正在生成答案解析...</span>
                      </div>
                      <div v-else>
                        <div class="ai-answer-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                          <strong>AI解析：</strong>
                          <el-button 
                            v-if="practiceForm.mode === 'drill' && aiAnswer && !aiLoading" 
                            type="success" 
                            size="small" 
                            @click="applyAIAnswerToDatabase"
                            class="apply-ai-btn"
                            :loading="applyingAI"
                          >
                            应该AI答案
                          </el-button>
                        </div>
                        <div class="ai-answer-content" v-if="aiAnswer">
                          <div v-html="sanitizeHtml(aiAnswer)" class="ai-content"></div>
                        </div>
                        <el-button 
                          v-if="!aiAnswer && !aiLoading && (currentQuestion.explanation || currentQuestion.analysis)" 
                          type="primary" 
                          size="small" 
                          @click="generateAIAnswer"
                          :loading="aiLoading"
                          class="generate-ai-btn"
                        >
                          获取AI解析
                        </el-button>
                        <div v-if="!aiAnswer && !aiLoading && !(currentQuestion.explanation || currentQuestion.analysis)">
                          <!-- 如果没有原有解析内容，自动加载AI解析 -->
                          <div class="ai-loading">
                            <el-icon class="is-loading"><Loading /></el-icon>
                            <span>AI正在生成答案解析...</span>
                          </div>
                        </div>

                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 填空题 -->
              <div class="options" v-if="currentQuestion.type === 'fill' || currentQuestion.type === 'fill_blank'">
                <el-input 
                  v-model="userAnswer"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入答案"
                  class="fill-input"
                  :disabled="practiceForm.mode === 'drill' && showAnswerForDrill"
                ></el-input>
                
                <!-- 刷题模式下显示答案和解析 -->
                <div v-if="practiceForm.mode === 'drill' && showAnswerForDrill">
                  <!-- 刷题模式下显示上一页和下一页按钮 -->
                  <div class="question-actions" style="margin-top: 20px; margin-bottom: 20px;">
                    <el-button @click="previousQuestion" :disabled="currentIndex === 0" class="nav-button">
                      上一题
                    </el-button>
                    <el-button type="primary" @click="skipOrNextQuestionInDrillMode" v-if="currentIndex < questions.length - 1" class="nav-button">
                      下一题
                    </el-button>
                    <el-button type="success" @click="submitPractice" v-if="currentIndex === questions.length - 1" :loading="submitting" class="submit-button">
                      提交答案
                    </el-button>
                  </div>
                  
                  <div class="drill-answer-section">
                    <div class="answer-explanation">
                      <p><strong>正确答案：</strong><span class="correct-answer">{{ formatAnswer(currentQuestion.correctAnswer) }}</span></p>
                      <div v-if="currentQuestion.explanation || currentQuestion.analysis" class="explanation-content">
                        <strong>解析：</strong>
                        <div v-html="sanitizeHtml(currentQuestion.explanation || currentQuestion.analysis)"></div>
                      </div>
                    </div>
                    
                    <!-- AI答案和解析 -->
                    <div class="ai-answer-section" v-if="showAIAnswer">
                      <div class="ai-loading" v-if="aiLoading">
                        <el-icon class="is-loading"><Loading /></el-icon>
                        <span>AI正在生成答案解析...</span>
                      </div>
                      <div v-else>
                        <div class="ai-answer-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                          <strong>AI解析：</strong>
                          <el-button 
                            v-if="practiceForm.mode === 'drill' && aiAnswer && !aiLoading" 
                            type="success" 
                            size="small" 
                            @click="applyAIAnswerToDatabase"
                            class="apply-ai-btn"
                            :loading="applyingAI"
                          >
                            应该AI答案
                          </el-button>
                        </div>
                        <div class="ai-answer-content" v-if="aiAnswer">
                          <div v-html="sanitizeHtml(aiAnswer)" class="ai-content"></div>
                        </div>
                        <el-button 
                          v-if="!aiAnswer && !aiLoading && (currentQuestion.explanation || currentQuestion.analysis)" 
                          type="primary" 
                          size="small" 
                          @click="generateAIAnswer"
                          :loading="aiLoading"
                          class="generate-ai-btn"
                        >
                          获取AI解析
                        </el-button>
                        <div v-if="!aiAnswer && !aiLoading && !(currentQuestion.explanation || currentQuestion.analysis)">
                          <!-- 如果没有原有解析内容，自动加载AI解析 -->
                          <div class="ai-loading">
                            <el-icon class="is-loading"><Loading /></el-icon>
                            <span>AI正在生成答案解析...</span>
                          </div>
                        </div>

                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 做题模式下显示上一页和下一页按钮 -->
              <div class="question-actions" v-if="practiceForm.mode === 'practice' || (practiceForm.mode === 'drill' && !showAnswerForDrill)">
                <el-button @click="previousQuestion" :disabled="currentIndex === 0" class="nav-button">
                  上一题
                </el-button>
                <el-button type="primary" @click="nextQuestion" v-if="currentIndex < questions.length - 1" class="nav-button">
                  下一题
                </el-button>
                <el-button type="success" @click="submitPractice" v-if="currentIndex === questions.length - 1 && !showResult" :loading="submitting" class="submit-button">
                  提交答案
                </el-button>
                <el-button type="primary" @click="restartPractice" v-if="currentIndex === questions.length - 1 && showResult" class="submit-button">
                  重新练习
                </el-button>
              </div>
            </div>
          </el-card>
          
          <div class="sidebar-container">
            <!-- 计时器卡片 -->
            <el-card class="timer-card" v-if="showTimer">
              <template #header>
                <div class="card-header">
                  <span>⏱️ 练习计时</span>
                </div>
              </template>
              <div class="timer-content">
                <div class="timer-display">{{ formatTime(practiceTime) }}</div>
                <p class="timer-tip">用时越短，效率越高</p>
              </div>
            </el-card>
            
            <!-- 答题卡 -->
            <el-card class="answer-card-panel" v-if="showAnswerCard">
              <template #header>
                <div class="card-header">
                  <span>📝 答题卡</span>
                </div>
              </template>
              <div class="answer-card-content">
                <div class="answer-card-grid">
                  <div 
                    v-for="item in getCurrentPageQuestionList" 
                    :key="item.originalIndex"
                    class="answer-card-item"
                    :class="{
                      'current': item.originalIndex === currentIndex,
                      'correct': userAnswers[item.originalIndex] && (showResult || isCorrect(item.question.correctAnswer || item.question.answer, userAnswers[item.originalIndex])),
                      'incorrect': showResult && userAnswers[item.originalIndex] && !isCorrect(item.question.correctAnswer || item.question.answer, userAnswers[item.originalIndex]),
                      'answered': userAnswers[item.originalIndex],
                      'unanswered': !userAnswers[item.originalIndex]
                    }"
                    @click="goToQuestion(item.originalIndex)"
                  >
                    {{ item.originalIndex + 1 }}
                  </div>
                </div>
                <!-- 分页控件 -->
                <div class="answer-card-pagination" v-if="answerCardTotalPages > 1">
                  <el-pagination
                    v-model:current-page="answerCardCurrentPage"
                    :page-size="answerCardPageSize"
                    :total="questions.length"
                    layout="prev, pager, next"
                    small
                    background
                    @current-change="handleAnswerCardPageChange"
                  />
                </div>
                <div class="answer-card-stats">
                  <div class="stat-item">
                    <div class="stat-color answered"></div>
                    <span>正确: {{ getCorrectCount() }}</span>
                  </div>
                  <div class="stat-item">
                    <div class="stat-color incorrect"></div>
                    <span>错误: {{ getIncorrectCount() }}</span>
                  </div>
                  <div class="stat-item">
                    <div class="stat-color unanswered"></div>
                    <span>未答: {{ (questions.length || 0) - getAnsweredCount() }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
      
      <div class="result-area" v-if="showResult">
        <el-card class="result-card">
          <template #header>
            <div class="card-header">
              <span><el-icon><Trophy /></el-icon> 练习结果</span>
              <div>
                <span class="practice-time">用时：{{ formatTime(practiceTime) }}</span>
                <span class="practice-time" style="margin-left: 20px;">平均用时：{{ formatTime(averageTimePerQuestion) }}</span>
              </div>
            </div>
          </template>
          
          <div class="result-content">
            <div class="result-summary">
              <h3 class="result-title">本次练习总结</h3>
              <p class="result-message">
                {{ getResultMessage(accuracy) }}
              </p>
            </div>
            
            <el-row :gutter="20" class="result-stats">
              <el-col :span="6">
                <div class="result-item">
                  <el-icon class="result-icon"><Notebook /></el-icon>
                  <h3>总题数</h3>
                  <p class="result-number">{{ questions.length || 0 }}</p>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="result-item">
                  <el-icon class="result-icon correct"><CircleCheck /></el-icon>
                  <h3>正确题数</h3>
                  <p class="result-number correct">{{ correctCount }}</p>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="result-item">
                  <el-icon class="result-icon error"><CircleClose /></el-icon>
                  <h3>错误题数</h3>
                  <p class="result-number error">{{ (questions.length || 0) - correctCount }}</p>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="result-item">
                  <el-icon class="result-icon"><DataAnalysis /></el-icon>
                  <h3>正确率</h3>
                  <p class="result-number">{{ accuracy }}%</p>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="result-item">
                  <el-icon class="result-icon"><Timer /></el-icon>
                  <h3>平均用时</h3>
                  <p class="result-number">{{ formatTime(averageTimePerQuestion) }}</p>
                </div>
              </el-col>
            </el-row>
            
            <div class="accuracy-chart">
              <el-progress type="circle" :percentage="accuracy" :width="120" :stroke-width="10">
                <template #default="{ percentage }">
                  <span class="progress-value">{{ percentage }}%</span>
                  <span class="progress-label">正确率</span>
                </template>
              </el-progress>
            </div>
            
            <div class="result-actions">
              <el-button type="primary" @click="restartPractice" class="action-button">
                <el-icon><RefreshRight /></el-icon> 重新练习
              </el-button>
              <el-button @click="viewAnswers" class="action-button">
                <el-icon><View /></el-icon> 查看答案
              </el-button>
              <el-button @click="goToHome" class="action-button">
                <el-icon><House /></el-icon> 返回首页
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 答案解析 -->
      <div class="answer-review" v-if="showAnswers">
        <el-card class="answer-card">
          <template #header>
            <div class="card-header">
              <span><el-icon><Reading /></el-icon> 答案解析</span>
              <el-button @click="returnToSettings" size="small">
                <el-icon><Back /></el-icon> 返回设置
              </el-button>
            </div>
          </template>
          
          <div class="answer-list">
            <div v-for="(question, index) in questions" :key="index" class="answer-item">
              <div class="answer-header">
                <h4><span class="question-index">第{{ index + 1 }}题{{ getQuestionCategoryText(question) }}：</span><span v-html="sanitizeHtml(question.content)" style="display: inline;"></span></h4>
                <el-tag :type="isCorrect(question.correctAnswer || question.answer, userAnswers[index]) ? 'success' : 'danger'" class="answer-tag">
                  {{ isCorrect(question.correctAnswer || question.answer, userAnswers[index]) ? '正确' : '错误' }}
                </el-tag>
              </div>
              
              <div class="answer-details">
                <p><strong>正确答案：</strong><span class="correct-answer">{{ formatAnswer(question.correctAnswer) }}</span></p>
                <p><strong>您的答案：</strong><span :class="isCorrect(question.correctAnswer || question.answer, userAnswers[index]) ? 'user-answer-correct' : 'user-answer-wrong'">{{ formatAnswer(userAnswers[index]) || '未作答' }}</span></p>
                <div v-if="question.explanation || question.analysis" class="answer-explanation">
                  <strong>解析：</strong>
                  <div v-html="sanitizeHtml(question.explanation || question.analysis)"></div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch, reactive, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '../api/request';
import axios from 'axios';
import { modifyQuestionContentImageSizeInHTML, modifyOptionImageSizeInHTML } from '@/utils/htmlUtils';
import {
  Select,
  Close,
  Timer,
  Document,
  QuestionFilled,
  ArrowLeft,
  ArrowRight,
  View,
  Refresh,
  House,
  Flag,
  Compass,
  ChatDotRound,
  DataLine,
  Finished,
  Files,
  Loading
} from '@element-plus/icons-vue';
import { addWrongQuestion } from '../api/wrongQuestions';
import { sendAIMessage } from '@/api/ai';

const props = defineProps({
  // 模块名称：politics(时政), commonSense(常识), language(言语), quantity(数量), judgment(判断), dataAnalysis(资料), vocabulary-accumulation(词汇积累)
  module: {
    type: String,
    required: true
  },
  // 获取题目的API路径
  fetchQuestionsApi: {
    type: String,
    required: true
  },
  // 提交答案的API路径
  submitAnswersApi: {
    type: String,
    required: true
  },
  // 用户进度API已移除
  // 是否显示填空题选项
  showFillOption: {
    type: Boolean,
    default: false
  },
  // 是否显示答题卡
  showAnswerCard: {
    type: Boolean,
    default: false
  },
  // 是否显示计时器
  showTimer: {
    type: Boolean,
    default: false
  },
  // 是否记录错题
  trackWrongQuestions: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['practice-completed']);

// 获取已答题数量
const getAnsweredCount = () => {
  return userAnswers.value.filter(answer => answer && answer !== '').length;
};

// 获取正确答案数量
const getCorrectCount = () => {
  if (!questions.value.length) return 0;
  return questions.value.filter((question, index) => {
    const userAns = userAnswers.value[index];
    const correctAns = question.correctAnswer || question.answer;
    return userAns && isCorrect(correctAns, userAns);
  }).length;
};

// 获取错误答案数量
const getIncorrectCount = () => {
  if (!questions.value.length) return 0;
  return questions.value.filter((question, index) => {
    const userAns = userAnswers.value[index];
    const correctAns = question.correctAnswer || question.answer;
    return userAns && !isCorrect(correctAns, userAns);
  }).length;
};

// 跳转到指定题目
const goToQuestion = (index: number) => {
  saveCurrentAnswer();
  currentIndex.value = index;
  loadAnswer();
};

// 处理答题卡分页切换
const handleAnswerCardPageChange = (page: number) => {
  answerCardCurrentPage.value = page;
};

const router = useRouter();
const loading = ref(false);
const submitting = ref(false);
const questions = ref<any[]>([]);
const currentIndex = ref(0);
const userAnswer = ref('');
const userAnswers = ref<any[]>([]);
const showResult = ref(false);
const showAnswers = ref(false);
const correctCount = ref(0);
const practiceTime = ref(0);
const timerInterval = ref(null);
const showAnswerForDrill = ref(false); // 添加刷题模式答案显示控制

// 添加状态以跟踪是否已加载初始数据
const isInitialDataLoaded = ref(false);

// 答题卡分页相关数据
const answerCardPageSize = ref(20); // 每页显示的题目数量
const answerCardCurrentPage = ref(1); // 当前页码

// AI相关响应式数据
const showAIAnswer = ref(false);
const aiLoading = ref(false);
const aiAnswer = ref('');
const applyingAI = ref(false); // 添加应用AI答案的状态
// AI解析缓存
const aiAnswerCache = ref<Record<string, string>>({}); // 用于缓存每道题的AI解析内容

// 用户进度功能已移除

// 在practiceForm中添加subCategory字段
const practiceForm = reactive({
  count: 0, // 0表示全部题目
  type: '',
  questionType: '', // 新增判断题目类型
  category: '',
  subCategory: '', // 添加小类别字段
  module: '', // 添加module属性
  mode: 'practice' // 添加练习模式字段，默认为做题模式
});

// 申论大类别选项
const shenlunCategories = [
  { value: '概括归纳', label: '概括归纳' },
  { value: '综合分析', label: '综合分析' },
  { value: '解决问题', label: '解决问题' },
  { value: '公文写作', label: '公文写作' },
  { value: '文章写作', label: '文章写作' }
];

// 申论小类别选项
const shenlunSubCategories = [
  // 概括归纳
  { value: '概括题', label: '概括题', parent: '概括归纳' },
  { value: '归纳题', label: '归纳题', parent: '概括归纳' },
  
  // 综合分析
  { value: '词句解释', label: '词句解释', parent: '综合分析' },
  { value: '观点分析', label: '观点分析', parent: '综合分析' },
  { value: '现象分析', label: '现象分析', parent: '综合分析' },
  { value: '要素分析', label: '要素分析', parent: '综合分析' },
  { value: '比较分析', label: '比较分析', parent: '综合分析' },
  
  // 解决问题
  { value: '单一对策', label: '单一对策', parent: '解决问题' },
  { value: '复合对策', label: '复合对策', parent: '解决问题' },
  { value: '变异对策', label: '变异对策', parent: '解决问题' },
  
  // 公文写作
  { value: '普适类', label: '普适类', parent: '公文写作' },
  { value: '提纲类', label: '提纲类', parent: '公文写作' },
  { value: '要点类', label: '要点类', parent: '公文写作' },
  
  // 文章写作
  { value: '解释类', label: '解释类', parent: '文章写作' },
  { value: '分析类', label: '分析类', parent: '文章写作' },
  { value: '对策类', label: '对策类', parent: '文章写作' }
];

// 六大模块分类选项
const moduleCategories: Record<string, Array<{ value: string; label: string }>> = {
  // 时政模块分类（使用时间筛选，但保留分类选项以保持一致性）
  politics: [],
  
  // 常识模块分类
  commonSense: [
    { value: 'Politics', label: '政治' },
    { value: 'Economics', label: '经济' },
    { value: 'HistoryLiterature', label: '文史' },
    { value: 'ScienceLife', label: '科学与生活' },
    { value: 'Geography', label: '地理' },
    { value: 'Law', label: '法律' },
    { value: 'ManagementDocuments', label: '管理与公文' }
  ],
  
  // 言语模块分类
  language: [
    { value: 'SegRead', label: '片段阅读' },
    { value: 'SenExp', label: '语句表达' },
    { value: 'LogFill', label: '逻辑填空' }
  ],
  
  // 数量模块分类
  quantitative: [
    { value: 'MulCha', label: '倍数特性' },
    { value: 'EquPro', label: '方程问题' },
    { value: 'AriGeoSeq', label: '等差数列和等比数列' },
    { value: 'PerPro', label: '周期问题' },
    { value: 'EngPro', label: '工程问题' },
    { value: 'GeoPro', label: '几何问题' },
    { value: 'IncExcPro', label: '容斥原理问题' },
    { value: 'ExtValPro', label: '最值问题' },
    { value: 'AgePro', label: '年龄问题' },
    { value: 'SolPro', label: '溶液问题' },
    { value: 'PlanEquPro', label: '植树与方程问题' },
    { value: 'EcoPro', label: '经济利润问题' },
    { value: 'TraPro', label: '行程问题' },
    { value: 'ComPermPro', label: '排列组合问题' },
    { value: 'EasyNumPro', label: '数量易拿分小题型' }
  ],
  
  // 判断模块分类
  judgment: [
    { value: 'DefRea', label: '定义推理' },
    { value: 'AnaRea', label: '类比推理' },
    { value: 'LogRea', label: '逻辑推理' },
    { value: 'GraRea', label: '图形推理' }
  ],
  
  // 资料模块分类
  dataAnalysis: [
    { value: 'FastCal', label: '八大常用速算技巧' },
    { value: 'BaseVal', label: '基期量' },
    { value: 'CurrVal', label: '现期量' },
    { value: 'GrowthRt', label: '增长率' },
    { value: 'GrowthAmt', label: '增长量' },
    { value: 'IntvGrowth', label: '间隔增长率' },
    { value: 'ProdGrowth', label: '乘积增长率' },
    { value: 'AnnGrowth', label: '年均增长率' },
    { value: 'MixGrowth', label: '混合增长率' },
    { value: 'Proportion', label: '比重' },
    { value: 'Average', label: '平均数' },
    { value: 'Multiple', label: '倍数' },
    { value: 'ANotA', label: 'A与非A思想' },
    { value: 'CompAnaly', label: '综合分析' }
  ]
};

// 六大模块子类别选项
const allSubCategories: Record<string, Array<{ value: string; label: string; parent: string }>> = {
  // 常识模块子分类
  Politics: [
    { value: 'CurrentPolitics', label: '时事政治', parent: 'Politics' },
    { value: 'PolicyInterpretation', label: '政策解读', parent: 'Politics' },
    { value: 'PoliticalTheory', label: '政治理论', parent: 'Politics' }
  ],
  Economics: [
    { value: 'MacroEconomics', label: '宏观经济', parent: 'Economics' },
    { value: 'MicroEconomics', label: '微观经济', parent: 'Economics' },
    { value: 'EconomicPolicy', label: '经济政策', parent: 'Economics' }
  ],
  HistoryLiterature: [
    { value: 'ChineseHistory', label: '中国历史', parent: 'HistoryLiterature' },
    { value: 'WorldHistory', label: '世界历史', parent: 'HistoryLiterature' },
    { value: 'LiteraryKnowledge', label: '文学常识', parent: 'HistoryLiterature' }
  ],
  ScienceLife: [
    { value: 'NaturalScience', label: '自然科学', parent: 'ScienceLife' },
    { value: 'LifeCommonSense', label: '生活常识', parent: 'ScienceLife' },
    { value: 'TechnologyFrontier', label: '科技前沿', parent: 'ScienceLife' }
  ],
  Geography: [
    { value: 'PhysicalGeography', label: '自然地理', parent: 'Geography' },
    { value: 'HumanGeography', label: '人文地理', parent: 'Geography' },
    { value: 'GeographicalKnowledge', label: '地理常识', parent: 'Geography' }
  ],
  Law: [
    { value: 'ConstitutionalLaw', label: '宪法法律', parent: 'Law' },
    { value: 'AdministrativeLaw', label: '行政法', parent: 'Law' },
    { value: 'CivilLaw', label: '民法', parent: 'Law' }
  ],
  ManagementDocuments: [
    { value: 'Management', label: '管理学', parent: 'ManagementDocuments' },
    { value: 'OfficialDocumentWriting', label: '公文写作', parent: 'ManagementDocuments' },
    { value: 'AdministrativeManagement', label: '行政管理', parent: 'ManagementDocuments' }
  ],
  
  // 言语模块子分类
  SegRead: [
    { value: 'CentralComprehension', label: '中心理解题', parent: 'SegRead' },
    { value: 'DetailJudgment', label: '细节判断题', parent: 'SegRead' }
  ],
  SenExp: [
    { value: 'DiscourseSelection', label: '接语选择题', parent: 'SenExp' },
    { value: 'SentenceFilling', label: '语句填空题', parent: 'SenExp' },
    { value: 'SentenceOrdering', label: '语句排序题', parent: 'SenExp' }
  ],
  LogFill: [
    { value: 'WordAnalysis', label: '词的辨析', parent: 'LogFill' },
    { value: 'ContextualAnalysis', label: '语境分析', parent: 'LogFill' }
  ],
  
  // 数量模块子分类
  MulCha: [
    { value: 'Parity', label: '奇偶性', parent: 'MulCha' },
    { value: 'Divisibility', label: '整除特性', parent: 'MulCha' },
    { value: 'RatioMultiple', label: '比例倍数', parent: 'MulCha' }
  ],
  EquPro: [
    { value: 'LinearEquation', label: '一元一次方程', parent: 'EquPro' },
    { value: 'BinaryLinearEquation', label: '二元一次方程', parent: 'EquPro' },
    { value: 'IndeterminateEquation', label: '不定方程', parent: 'EquPro' }
  ],
  AriGeoSeq: [
    { value: 'ArithmeticSequence', label: '等差数列', parent: 'AriGeoSeq' },
    { value: 'GeometricSequence', label: '等比数列', parent: 'AriGeoSeq' }
  ],
  PerPro: [
    { value: 'CycleIdentification', label: '周期识别', parent: 'PerPro' },
    { value: 'CycleCalculation', label: '周期计算', parent: 'PerPro' }
  ],
  EngPro: [
    { value: 'WorkTimeProblem', label: '工程时间问题', parent: 'EngPro' },
    { value: 'WorkEfficiencyProblem', label: '工程效率问题', parent: 'EngPro' }
  ],
  GeoPro: [
    { value: 'PlaneGeometry', label: '平面几何', parent: 'GeoPro' },
    { value: 'SolidGeometry', label: '立体几何', parent: 'GeoPro' }
  ],
  IncExcPro: [
    { value: 'TwoSetProblem', label: '两集合问题', parent: 'IncExcPro' },
    { value: 'ThreeSetProblem', label: '三集合问题', parent: 'IncExcPro' }
  ],
  ExtValPro: [
    { value: 'MaximumProblem', label: '最大值问题', parent: 'ExtValPro' },
    { value: 'MinimumProblem', label: '最小值问题', parent: 'ExtValPro' }
  ],
  AgePro: [
    { value: 'AgeRelationship', label: '年龄关系', parent: 'AgePro' },
    { value: 'AgeCalculation', label: '年龄计算', parent: 'AgePro' }
  ],
  SolPro: [
    { value: 'SolutionConcentration', label: '溶液浓度', parent: 'SolPro' },
    { value: 'SolutionMixing', label: '溶液混合', parent: 'SolPro' }
  ],
  PlanEquPro: [
    { value: 'PlantingProblem', label: '植树问题', parent: 'PlanEquPro' },
    { value: 'EquationApplication', label: '方程应用', parent: 'PlanEquPro' }
  ],
  EcoPro: [
    { value: 'ProfitProblem', label: '利润问题', parent: 'EcoPro' },
    { value: 'InterestProblem', label: '利息问题', parent: 'EcoPro' }
  ],
  TraPro: [
    { value: 'MeetingProblem', label: '相遇问题', parent: 'TraPro' },
    { value: 'PursuitProblem', label: '追及问题', parent: 'TraPro' }
  ],
  ComPermPro: [
    { value: 'CombinationProblem', label: '组合问题', parent: 'ComPermPro' },
    { value: 'PermutationProblem', label: '排列问题', parent: 'ComPermPro' }
  ],
  EasyNumPro: [
    { value: 'SimpleCalculation', label: '简单计算', parent: 'EasyNumPro' },
    { value: 'SpecialValueMethod', label: '特殊值法', parent: 'EasyNumPro' }
  ],
  
  // 判断模块子分类
  DefRea: [
    { value: 'SingleDefinition', label: '单定义', parent: 'DefRea' },
    { value: 'MultipleDefinition', label: '多定义', parent: 'DefRea' }
  ],
  AnaRea: [
    { value: 'AttributeAnalogy', label: '属性类比', parent: 'AnaRea' },
    { value: 'StructureAnalogy', label: '结构类比', parent: 'AnaRea' }
  ],
  LogRea: [
    { value: 'TranslationReasoning', label: '翻译推理', parent: 'LogRea' },
    { value: 'LogicalCalculation', label: '逻辑计算', parent: 'LogRea' }
  ],
  GraRea: [
    { value: 'NinePalaceGrid', label: '九宫格', parent: 'GraRea' },
    { value: 'SpaceReconstruction', label: '空间重构', parent: 'GraRea' }
  ],
  
  // 资料模块子分类
  FastCal: [
    { value: 'TruncationMethod', label: '截位法', parent: 'FastCal' },
    { value: 'DirectDivision', label: '直除法', parent: 'FastCal' }
  ],
  BaseVal: [
    { value: 'BasePeriodCalculation', label: '基期计算', parent: 'BaseVal' },
    { value: 'BasePeriodComparison', label: '基期比较', parent: 'BaseVal' }
  ],
  CurrVal: [
    { value: 'CurrentPeriodCalculation', label: '现期计算', parent: 'CurrVal' },
    { value: 'CurrentPeriodComparison', label: '现期比较', parent: 'CurrVal' }
  ],
  GrowthRt: [
    { value: 'GrowthRateCalculation', label: '增长率计算', parent: 'GrowthRt' },
    { value: 'GrowthRateComparison', label: '增长率比较', parent: 'GrowthRt' }
  ],
  GrowthAmt: [
    { value: 'GrowthAmountCalculation', label: '增长量计算', parent: 'GrowthAmt' },
    { value: 'GrowthAmountComparison', label: '增长量比较', parent: 'GrowthAmt' }
  ],
  IntvGrowth: [
    { value: 'IntervalGrowthRate', label: '间隔增长率', parent: 'IntvGrowth' },
    { value: 'IntervalBasePeriod', label: '间隔基期', parent: 'IntvGrowth' }
  ],
  ProdGrowth: [
    { value: 'ProductGrowthRate', label: '乘积增长率', parent: 'ProdGrowth' },
    { value: 'ProductBasePeriod', label: '乘积基期', parent: 'ProdGrowth' }
  ],
  AnnGrowth: [
    { value: 'AnnualGrowthRate', label: '年均增长率', parent: 'AnnGrowth' },
    { value: 'AnnualAverageGrowth', label: '年均增长量', parent: 'AnnGrowth' }
  ],
  MixGrowth: [
    { value: 'MixedGrowthRate', label: '混合增长率', parent: 'MixGrowth' },
    { value: 'MixedBasePeriod', label: '混合基期', parent: 'MixGrowth' }
  ],
  Proportion: [
    { value: 'ProportionCalculation', label: '比重计算', parent: 'Proportion' },
    { value: 'ProportionComparison', label: '比重比较', parent: 'Proportion' }
  ],
  Average: [
    { value: 'AverageCalculation', label: '平均数计算', parent: 'Average' },
    { value: 'AverageComparison', label: '平均数比较', parent: 'Average' }
  ],
  Multiple: [
    { value: 'MultipleCalculation', label: '倍数计算', parent: 'Multiple' },
    { value: 'MultipleComparison', label: '倍数比较', parent: 'Multiple' }
  ],
  ANotA: [
    { value: 'ANotAConcept', label: 'A与非A概念', parent: 'ANotA' },
    { value: 'ANotAApplication', label: 'A与非A应用', parent: 'ANotA' }
  ],
  CompAnaly: [
    { value: 'ComprehensiveCalculation', label: '综合计算', parent: 'CompAnaly' },
    { value: 'ComprehensiveComparison', label: '综合比较', parent: 'CompAnaly' }
  ]
};

// 根据大类别过滤小类别选项（申论模块）
const filteredSubCategories = computed(() => {
  if (!practiceForm.category) {
    return [];
  }
  return shenlunSubCategories.filter(item => item.parent === practiceForm.category);
});

// 根据大类别过滤小类别选项（六大模块）
const filteredSubCategoriesAll = computed(() => {
  if (!practiceForm.category) {
    return [];
  }
  return allSubCategories[practiceForm.category] || [];
});

// 处理大类别变化
const handleCategoryChange = () => {
  // 清空小类别选择
  practiceForm.subCategory = '';
  
  // 特殊处理时政模块
  if (props.module === 'politics') {
    // 时政模块使用时间筛选，不使用category字段
    practiceForm.category = '';
  }
};

// 模块配置
const moduleConfig = {
  wrongQuestions: {
    name: '错题本',
    icon: Files,
    description: '巩固知识点，提高答题正确率',
    tips: [
      '针对性复习错题，查漏补缺',
      '分析错误原因，总结解题思路',
      '定期复习，加深记忆'
    ],
    categories: [] as { label: string; value: string }[] // 添加categories属性并指定类型
  },
  politics: {
    name: '时政',
    icon: Flag,
    description: '掌握时事政治，了解国家大事',
    tips: [
      '关注时事热点，积累政治常识',
      '理解政策背景，把握发展趋势',
      '结合实际案例，加深理解'
    ],
    categories: [
      { label: '政治', value: 'Politics' },
      { label: '经济', value: 'Economics' },
      { label: '文史', value: 'HistoryLiterature' },
      { label: '科学与生活', value: 'ScienceLife' },
      { label: '地理', value: 'Geography' },
      { label: '法律', value: 'Law' },
      { label: '管理与公文', value: 'ManagementDocuments' }
    ] as { label: string; value: string }[] // 添加categories属性并指定类型
  },
  commonSense: {
    name: '常识',
    icon: Compass,
    description: '拓展知识面，提升综合素养',
    tips: [
      '广泛涉猎各领域知识',
      '注重知识点之间的联系',
      '多做练习，巩固记忆'
    ],
    categories: [
      { label: '政治', value: 'Politics' },
      { label: '经济', value: 'Economics' },
      { label: '文史', value: 'HistoryLiterature' },
      { label: '科学与生活', value: 'ScienceLife' },
      { label: '地理', value: 'Geography' },
      { label: '法律', value: 'Law' },
      { label: '管理与公文', value: 'ManagementDocuments' }
    ] as { label: string; value: string }[] // 添加categories属性并指定类型
  },
  language: {
    name: '言语理解',
    icon: ChatDotRound,
    description: '提升语言文字运用能力',
    tips: [
      '注重语感训练，多读多练',
      '掌握解题技巧，提高效率',
      '积累词汇，扩大知识面'
    ],
    categories: [
      { label: '片段阅读', value: 'SegRead' },
      { label: '语句表达', value: 'SenExp' },
      { label: '逻辑填空', value: 'LogFill' }
    ] as { label: string; value: string }[] // 添加categories属性并指定类型
  },
  judgment: {
    name: '判断推理',
    icon: QuestionFilled,
    description: '锻炼逻辑思维，提升推理能力',
    tips: [
      '培养逻辑思维能力',
      '掌握各类题型特点',
      '多练习，提高解题速度'
    ],
    categories: [
      { label: '定义推理', value: 'DefRea' },
      { label: '类比推理', value: 'AnaRea' },
      { label: '逻辑推理', value: 'LogRea' },
      { label: '图形推理', value: 'GraRea' }
    ] as { label: string; value: string }[] // 添加categories属性并指定类型
  },
  quantitative: {
    name: '数量关系',
    icon: DataLine,
    description: '提升数学运算能力',
    tips: [
      '掌握基本数学公式',
      '培养数学思维',
      '多练习计算技巧'
    ],
    categories: [
      { label: '倍数特性', value: 'MulCha' },
      { label: '方程问题', value: 'EquPro' },
      { label: '等差数列和等比数列', value: 'AriGeoSeq' },
      { label: '周期问题', value: 'PerPro' },
      { label: '工程问题', value: 'EngPro' },
      { label: '几何问题', value: 'GeoPro' },
      { label: '容斥原理问题', value: 'IncExcPro' },
      { label: '最值问题', value: 'ExtValPro' },
      { label: '年龄问题', value: 'AgePro' },
      { label: '溶液问题', value: 'SolPro' },
      { label: '植树与方程问题', value: 'PlanEquPro' },
      { label: '经济利润问题', value: 'EcoPro' },
      { label: '行程问题', value: 'TraPro' },
      { label: '排列组合问题', value: 'ComPermPro' },
      { label: '数量易拿分小题型', value: 'EasyNumPro' }
    ] as { label: string; value: string }[] // 添加categories属性并指定类型
  },
  dataAnalysis: {
    name: '资料分析',
    icon: Document,
    description: '提升数据分析和处理能力',
    tips: [
      '快速定位关键信息',
      '掌握计算技巧',
      '提高阅读理解能力'
    ],
    categories: [
      { label: '八大常用速算技巧', value: 'FastCal' },
      { label: '基期量', value: 'BaseVal' },
      { label: '现期量', value: 'CurrVal' },
      { label: '增长率', value: 'GrowthRt' },
      { label: '增长量', value: 'GrowthAmt' },
      { label: '间隔增长率', value: 'IntvGrowth' },
      { label: '乘积增长率', value: 'ProdGrowth' },
      { label: '年均增长率', value: 'AnnGrowth' },
      { label: '混合增长率', value: 'MixGrowth' },
      { label: '比重', value: 'Proportion' },
      { label: '平均数', value: 'Average' },
      { label: '倍数', value: 'Multiple' },
      { label: 'A与非A思想', value: 'ANotA' },
      { label: '综合分析', value: 'CompAnaly' }
    ] as { label: string; value: string }[] // 添加categories属性并指定类型
  },
  'vocabulary-accumulation': {
    name: '词汇积累',
    icon: Document,
    description: '扩大词汇量，提升语言表达能力',
    tips: [
      '每天坚持学习新词汇',
      '注重词汇的实际运用',
      '通过阅读积累词汇'
    ],
    categories: [] as { label: string; value: string }[] // 添加categories属性并指定类型
  }
};

// 计算属性
const currentQuestion = computed(() => {
  return questions.value[currentIndex.value] || null;
});

const currentModule = computed(() => {
  const moduleKey = props.module as keyof typeof moduleConfig;
  return moduleConfig[moduleKey] || {};
});

const moduleName = computed(() => {
  return currentModule.value.name || '练习';
});

// 获取显示的模块名称（根据练习模式显示不同前缀）
const getDisplayModuleName = () => {
  // 根据练习模式显示不同的前缀
  const prefix = practiceForm.mode === 'drill' ? '刷题' : '做题';
  
  // 特殊处理错题本模块
  if (props.module === 'wrongQuestions') {
    // 如果选择了模块，显示模块名称，否则显示"全部"
    if (practiceForm.module) {
      const selectedModule = moduleConfig[practiceForm.module as keyof typeof moduleConfig];
      const moduleName = selectedModule ? selectedModule.name : practiceForm.module;
      return `${prefix}-错题本-${moduleName}`;
    } else {
      return `${prefix}-错题本-全部`;
    }
  }
  
  return prefix + '-' + (currentModule.value.name || '练习') + '-全部';
};

// 获取当前分类文本
const getCurrentCategoryText = () => {
  // 时政模块不显示分类信息
  if (props.module === 'politics') return '';
  
  // 如果没有选择分类，显示"-全部"
  if (!practiceForm.category) return '-全部';
  
  // 查找大类别名称
  let categoryLabel = '';
  if (props.module === 'shenlun') {
    const category = shenlunCategories.find(cat => cat.value === practiceForm.category);
    categoryLabel = category ? category.label : '';
  } else if (['commonSense', 'language', 'judgment', 'quantitative', 'dataAnalysis'].includes(props.module)) {
    const categories = moduleCategories[props.module as keyof typeof moduleCategories] || [];
    const category = categories.find(cat => cat.value === practiceForm.category);
    categoryLabel = category ? category.label : '';
  }
  
  // 如果没有小类别，只返回大类别
  if (!practiceForm.subCategory) {
    return categoryLabel ? `-${categoryLabel}` : '-全部';
  }
  
  // 查找小类别名称
  let subCategoryLabel = '';
  if (props.module === 'shenlun') {
    const subCategory = shenlunSubCategories.find(sub => sub.value === practiceForm.subCategory);
    subCategoryLabel = subCategory ? subCategory.label : '';
  } else if (['commonSense', 'language', 'judgment', 'quantitative', 'dataAnalysis'].includes(props.module)) {
    const subCategories = allSubCategories[practiceForm.category] || [];
    const subCategory = subCategories.find(sub => sub.value === practiceForm.subCategory);
    subCategoryLabel = subCategory ? subCategory.label : '';
  }
  
  // 返回大类别和小类别
  if (categoryLabel && subCategoryLabel) {
    return `-${categoryLabel}-${subCategoryLabel}`;
  } else if (categoryLabel) {
    return `-${categoryLabel}`;
  } else {
    return '-全部';
  }
};

// 获取题目分类文本
const getQuestionCategoryText = (question: any) => {
  // 时政模块不显示分类信息
  if (props.module === 'politics') return '';
  
  // 如果没有选择分类，显示"-全部"
  if (!question.category && !question.subCategory) return '-全部';
  
  // 查找大类别名称
  let categoryLabel = '';
  if (props.module === 'shenlun') {
    const category = shenlunCategories.find(cat => cat.value === question.category);
    categoryLabel = category ? category.label : '';
  } else if (['commonSense', 'language', 'judgment', 'quantitative', 'dataAnalysis'].includes(props.module)) {
    const categories = moduleCategories[props.module as keyof typeof moduleCategories] || [];
    const category = categories.find(cat => cat.value === question.category);
    categoryLabel = category ? category.label : '';
  }
  
  // 如果没有小类别，只返回大类别
  if (!question.subCategory) {
    return categoryLabel ? `-${categoryLabel}` : '-全部';
  }
  
  // 查找小类别名称
  let subCategoryLabel = '';
  if (props.module === 'shenlun') {
    const subCategory = shenlunSubCategories.find(sub => sub.value === question.subCategory);
    subCategoryLabel = subCategory ? subCategory.label : '';
  } else if (['commonSense', 'language', 'judgment', 'quantitative', 'dataAnalysis'].includes(props.module)) {
    const subCategories = allSubCategories[question.category] || [];
    const subCategory = subCategories.find(sub => sub.value === question.subCategory);
    subCategoryLabel = subCategory ? subCategory.label : '';
  }
  
  // 返回大类别和小类别
  if (categoryLabel && subCategoryLabel) {
    return `-${categoryLabel}-${subCategoryLabel}`;
  } else if (categoryLabel) {
    return `-${categoryLabel}`;
  } else {
    return '-全部';
  }
};

const moduleDescription = computed(() => {
  return currentModule.value.description || '';
});

const moduleTips = computed(() => {
  return currentModule.value.tips || [];
});

const accuracy = computed(() => {
  if (questions.value.length === 0) return 0;
  return Math.round((correctCount.value / questions.value.length) * 100);
});

// 计算平均每道题用时
const averageTimePerQuestion = computed(() => {
  if (questions.value.length === 0) return 0;
  return practiceTime.value / questions.value.length;
});

// 计算已答题数量
const answeredCount = computed(() => {
  return userAnswers.value.filter(answer => answer && answer !== '').length;
});

// 计算答题进度
const progressPercentage = computed(() => {
  if (questions.value.length === 0) return 0;
  return Math.round((answeredCount.value / questions.value.length) * 100);
});

// 方法
const returnHome = () => {
  router.push('/');
};

const goToHome = () => {
  router.push('/');
};

const percentageFormat = (percentage: number) => {
  return `${percentage}%`;
};

const startPractice = async (externalParams?: any) => {
  loading.value = true;
  try {
    // 如果提供了外部参数，使用外部参数；否则使用表单参数
    let params: Record<string, any> = {};
    
    if (externalParams) {
      // 使用外部参数
      // 从PracticeSettings传递的参数结构中提取实际参数
      params = externalParams.params ? { ...externalParams.params } : { ...externalParams };
      // 同时更新表单以保持一致性
      practiceForm.count = (externalParams.params ? externalParams.params.count : externalParams.count) || 0;
      practiceForm.type = (externalParams.params ? externalParams.params.questionType : externalParams.questionType) || '';
      practiceForm.category = (externalParams.params ? externalParams.params.category : externalParams.category) || '';
      practiceForm.subCategory = (externalParams.params ? externalParams.params.subCategory : externalParams.subCategory) || '';
      practiceForm.module = (externalParams.params ? externalParams.params.module : externalParams.module) || '';
      // 正确处理mode参数
      practiceForm.mode = externalParams.mode || (externalParams.params ? externalParams.params.mode : 'practice') || 'practice';
      
      // 确保mode参数也在params中
      if (!params.mode && externalParams.mode) {
        params.mode = externalParams.mode;
      } else if (!params.mode && externalParams.params && externalParams.params.mode) {
        params.mode = externalParams.params.mode;
      } else if (!params.mode) {
        params.mode = 'practice';
      }
    } else {
      // 验证小分类是否有效
      if (practiceForm.category && practiceForm.subCategory) {
        let isValidSubCategory = false;
        
        // 检查申论模块
        if (props.module === 'shenlun') {
          isValidSubCategory = shenlunSubCategories.some(item => 
            item.parent === practiceForm.category && item.value === practiceForm.subCategory
          );
        } 
        // 检查六大题库模块
        else if (['politics', 'commonSense', 'language', 'judgment', 'quantitative', 'dataAnalysis'].includes(props.module)) {
          const subCategories = allSubCategories[practiceForm.category] || [];
          isValidSubCategory = subCategories.some(item => item.value === practiceForm.subCategory);
        }
        
        // 如果小分类不属于当前大分类，显示错误信息
        if (!isValidSubCategory) {
          ElMessage.error('选择的小分类与大分类不匹配，请重新选择');
          loading.value = false;
          return;
        }
      }
      
      // 获取分类和子分类的中文标签
      let categoryLabel = '';
      let subCategoryLabel = '';
      
      // 获取大分类中文标签
      if (practiceForm.category) {
        if (props.module === 'shenlun') {
          const category = shenlunCategories.find(cat => cat.value === practiceForm.category);
          categoryLabel = category ? category.label : practiceForm.category;
        } else if (['commonSense', 'language', 'judgment', 'quantitative', 'dataAnalysis'].includes(props.module)) {
          const categories = moduleCategories[props.module as keyof typeof moduleCategories] || [];
          const category = categories.find(cat => cat.value === practiceForm.category);
          categoryLabel = category ? category.label : practiceForm.category;
        }
      }
      
      // 获取小分类中文标签
      if (practiceForm.subCategory) {
        if (props.module === 'shenlun') {
          const subCategory = shenlunSubCategories.find(sub => sub.value === practiceForm.subCategory);
          subCategoryLabel = subCategory ? subCategory.label : practiceForm.subCategory;
        } else if (['commonSense', 'language', 'judgment', 'quantitative', 'dataAnalysis'].includes(props.module)) {
          const subCategories = allSubCategories[practiceForm.category] || [];
          const subCategory = subCategories.find(sub => sub.value === practiceForm.subCategory);
          subCategoryLabel = subCategory ? subCategory.label : practiceForm.subCategory;
        }
      }
      
      // 当count为0时，表示获取全部题目，需要传递0而不是undefined
      params = {
        count: practiceForm.count >= 0 ? practiceForm.count : undefined, // 当count为0时也传递，表示获取全部
        questionType: practiceForm.type || undefined,
        category: categoryLabel || undefined,  // 使用中文标签
        subCategory: subCategoryLabel || undefined,  // 使用中文标签
        module: practiceForm.module || undefined,
        mode: practiceForm.mode || 'practice', // 添加练习模式参数
        orderBy: 'question_id', // 添加排序字段
        orderType: 'asc' // 添加排序方式
      };
    }
    
    // 特殊处理时政模块的时间筛选
    if (props.module === 'politics' && params.category && !externalParams) {
      params.date = params.category;
      delete params.category;
    }
    
    // 过滤掉空值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === '') {
        delete params[key];
      }
    });
    
    console.log('发送请求参数:', params);
    const response = await request.get(props.fetchQuestionsApi, { params });
    
    if (response.data && response.data.length > 0) {
      questions.value = response.data;
      userAnswers.value = new Array(questions.value.length).fill('');
      currentIndex.value = 0;
      userAnswer.value = '';
      showResult.value = false;
      showAnswers.value = false;
      showAnswerForDrill.value = false; // 重置刷题模式答案显示状态
      

      
      // 保存练习状态到 sessionStorage
      savePracticeState();
      
      // 开始计时
      if (props.showTimer) {
        startTimer();
      }
    } else {
      ElMessage.warning('该模块下没有错题，请选择其他模块');
      // 没有题目时返回设置页面
      returnToSettings();
    }
  } catch (error: any) {
    console.error('获取题目失败:', error);
    // 打印详细的错误信息以便调试
    console.log('详细错误信息:', {
      error: error,
      response: error.response,
      message: error.message,
      data: error.response?.data
    });
    
    // 检查是否是未登录或登录过期的错误
    let isAuthError = false;
    
    // 精确检查未登录或登录过期错误 - 根据后端返回的具体格式
    if (error.response && error.response.data) {
      const data = error.response.data;
      // 精确匹配后端返回的未登录错误格式: {code: 500, message: '未登录或登录已过期', ...}
      if (data.code === 500 && data.message === '未登录或登录已过期') {
        isAuthError = true;
      }
    }
    
    // 如果是通过axios拦截器传递的认证错误
    if (error.message === 'AUTH_ERROR') {
      isAuthError = true;
    }
    
    if (isAuthError) {
      ElMessage.error('未登录或登录已过期');
    } else {
      ElMessage.error('获取题目失败，请稍后重试');
    }
  } finally {
    loading.value = false;
  }
};

const startTimer = () => {
  practiceTime.value = 0;
  timerInterval.value = setInterval(() => {
    practiceTime.value++;
  }, 1000) as any;
};

const stopTimer = () => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value);
    timerInterval.value = null;
  }
};

const formatTime = (seconds: number) => {
  // 如果是小数，保留一位小数
  if (seconds % 1 !== 0) {
    const totalSeconds = Math.round(seconds * 10) / 10; // 保留一位小数
    if (totalSeconds < 60) {
      return `${totalSeconds.toFixed(1)}秒`;
    } else {
      const minutes = Math.floor(totalSeconds / 60);
      const remainingSeconds = Math.round(totalSeconds % 60);
      return `${minutes}分${remainingSeconds}秒`;
    }
  } else {
    // 如果是整数，按原来的方式处理
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  }
};

const saveCurrentAnswer = () => {
  if (currentIndex.value >= 0 && currentIndex.value < userAnswers.value.length) {
    userAnswers.value[currentIndex.value] = userAnswer.value as never;
    // 保存练习状态到 sessionStorage
    savePracticeState();
  }
};

// 添加保存练习状态的函数
const savePracticeState = () => {
  const state = {
    questions: questions.value,
    currentIndex: currentIndex.value,
    userAnswers: userAnswers.value,
    practiceTime: practiceTime.value,
    showAnswerForDrill: showAnswerForDrill.value,
    practiceMode: practiceForm.mode
  };
  sessionStorage.setItem('practiceState', JSON.stringify(state));
};

const loadAnswer = () => {
  if (currentIndex.value >= 0 && currentIndex.value < userAnswers.value.length) {
    userAnswer.value = userAnswers.value[currentIndex.value] || '';
  }
  // 切换题目时重置刷题模式的答案显示状态
  if (practiceForm.mode === 'drill') {
    // 在刷题模式下，只有当用户没有选择答案时才隐藏答案和解析
    // 如果用户已经选择了答案，保持答案和解析的显示
    if (!userAnswer.value) {
      showAnswerForDrill.value = false;
    }
    // 重置AI相关状态，但在刷题模式下保持showAIAnswer为true以显示AI区域
    // showAIAnswer.value = false;
    // 如果用户已经选择了答案，显示AI解析内容
    if (userAnswer.value) {
      // 检查是否有缓存的AI解析内容
      const currentQuestionId = questions.value[currentIndex.value]?.id || questions.value[currentIndex.value]?.questionId;
      if (currentQuestionId && aiAnswerCache.value[currentQuestionId]) {
        // 如果有缓存，使用缓存的AI解析内容
        aiAnswer.value = aiAnswerCache.value[currentQuestionId];
      } else {
        // 检查题目是否有原有解析内容
        const hasOriginalExplanation = questions.value[currentIndex.value]?.explanation || questions.value[currentIndex.value]?.analysis;
        if (!hasOriginalExplanation) {
          // 如果没有原有解析内容，自动加载AI解析
          generateAIAnswer();
        } else {
          // 如果有原有解析内容，清空AI解析内容，显示获取AI解析按钮
          aiAnswer.value = '';
        }
      }
      // aiLoading.value = false; // 不再需要这行，因为generateAIAnswer会设置aiLoading
      applyingAI.value = false; // 重置应用AI状态
      // 在刷题模式下保持AI区域显示
      showAIAnswer.value = true;
      // 在刷题模式下，如果用户已经选择了答案，应该显示答案和解析
      showAnswerForDrill.value = true;
    }
  } else {
    // 在做题模式下隐藏答案和解析
    showAnswerForDrill.value = false;
  }
};

// 获取当前页的题目索引范围
const getCurrentPageQuestions = computed(() => {
  const start = (answerCardCurrentPage.value - 1) * answerCardPageSize.value;
  const end = Math.min(start + answerCardPageSize.value, questions.value.length);
  return { start, end };
});

// 计算总页数
const answerCardTotalPages = computed(() => {
  return Math.ceil(questions.value.length / answerCardPageSize.value);
});

// 获取当前页的题目列表
const getCurrentPageQuestionList = computed(() => {
  const { start, end } = getCurrentPageQuestions.value;
  return questions.value.slice(start, end).map((question, index) => ({
    question,
    originalIndex: start + index
  }));
});

const previousQuestion = () => {
  if (currentIndex.value > 0) {
    saveCurrentAnswer();
    currentIndex.value--;
    loadAnswer();
    // 在刷题模式下切换到上一题时，检查用户是否已经选择了答案
    if (practiceForm.mode === 'drill') {
      // 如果用户已经选择了答案，保持答案和解析的显示
      showAnswerForDrill.value = !!userAnswer.value;
    }
    // 保存练习状态到 sessionStorage
    savePracticeState();
  }
};

const nextQuestion = () => {
  if (currentIndex.value < questions.value.length - 1) {
    saveCurrentAnswer();
    currentIndex.value++;
    loadAnswer();
    // 在刷题模式下切换到下一题时，检查用户是否已经选择了答案
    if (practiceForm.mode === 'drill') {
      // 如果用户已经选择了答案，保持答案和解析的显示
      showAnswerForDrill.value = !!userAnswer.value;
    }
  }
};

// 添加刷题模式下的下一题方法
const nextQuestionInDrillMode = () => {
  // 保存当前答案（如果有的话）
  if (userAnswer.value) {
    saveCurrentAnswer();
  }
  if (currentIndex.value < questions.value.length - 1) {
    currentIndex.value++;
    loadAnswer(); // 加载下一题的答案
    // 在刷题模式下切换到下一题时，检查用户是否已经选择了答案
    if (practiceForm.mode === 'drill') {
      // 如果用户已经选择了答案，保持答案和解析的显示
      showAnswerForDrill.value = !!userAnswer.value;
      // 同时显示AI解析区域
      if (userAnswer.value) {
        showAIAnswer.value = true;
      }
    }
    // 保存练习状态到 sessionStorage
    savePracticeState();
  } else {
    // 如果是最后一题，显示结果
    showResult.value = true;
    // 清除保存的练习状态
    sessionStorage.removeItem('practiceState');
  }
};

// 添加刷题模式下跳过或进入下一题的方法
const skipOrNextQuestionInDrillMode = () => {
  // 保存当前答案（如果有的话）
  if (userAnswer.value) {
    saveCurrentAnswer();
  }
  if (currentIndex.value < questions.value.length - 1) {
    currentIndex.value++;
    loadAnswer(); // 加载下一题的答案
    // 在刷题模式下切换到下一题时，检查用户是否已经选择了答案
    if (practiceForm.mode === 'drill') {
      // 如果用户已经选择了答案，保持答案和解析的显示
      showAnswerForDrill.value = !!userAnswer.value;
      // 同时显示AI解析区域
      if (userAnswer.value) {
        showAIAnswer.value = true;
      }
    }
    // 保存练习状态到 sessionStorage
    savePracticeState();
  } else {
    // 如果是最后一题，显示结果
    showResult.value = true;
    // 清除保存的练习状态
    sessionStorage.removeItem('practiceState');
  }
};

const submitPractice = async () => {
  // 做题模式下保存当前答案
  if (practiceForm.mode === 'practice') {
    saveCurrentAnswer();
  }
  
  // 设置提交状态
  submitting.value = true;
  
  // 计算正确答案数量
  correctCount.value = 0;
  const wrongQuestions: any[] = [];
  
  questions.value.forEach((question: any, index: number) => {
    const userAns = userAnswers.value[index];
    const correctAns = question.correctAnswer || question.answer;
    
    if (isCorrect(correctAns, userAns)) {
      correctCount.value++;
    } else if (props.trackWrongQuestions && userAns) {
      // 记录错题
      wrongQuestions.push({
        questionId: question.id || question.questionId,
        userId: question.userId, // 虽然后端会设置，但前端传递过去也无妨
        questionType: question.type || question.questionType || 'single', // 确保有题目类型
        title: question.title,
        content: question.content,
        options: question.options,
        correctAnswer: correctAns,
        difficulty: question.difficulty,
        explanation: question.explanation,
        // 时政模块特殊处理：不使用category字段存储时间
        category: props.module === 'politics' ? '' : question.category,
        subCategory: question.subCategory,
        module: props.module,
        status: 1, // 默认状态为1
        createTime: question.createTime,
        updateTime: question.updateTime,
        userAnswer: userAns,
      });
    }
  });
  
  // 停止计时
  stopTimer();
  
  // 提交答案到后端
  try {
    if (props.submitAnswersApi) {
      await request.post(props.submitAnswersApi, {
        answers: userAnswers.value,
        practiceTime: practiceTime.value,
        correctCount: correctCount.value,
        totalCount: questions.value.length,
        accuracy: accuracy.value
      });
      
      // 添加成功提示
      ElMessage.success('答案提交成功！');
    }
    
    // 批量添加错题
    if (wrongQuestions.length > 0) {
      try {
        await Promise.all(wrongQuestions.map(wq => addWrongQuestion(wq)));
        // 添加错题记录提示
        ElMessage.info(`已记录 ${wrongQuestions.length} 道错题到错题本`);
      } catch (error) {
        console.error('添加错题失败:', error);
        ElMessage.error('错题记录保存失败');
      }
    }
    
  } catch (error: any) {
    console.error('提交答案失败:', error);
    ElMessage.error('提交答案失败，但练习结果已保存');
  } finally {
    // 重置提交状态
    submitting.value = false;
  }
  
  showResult.value = true;
  // 清除保存的练习状态
  sessionStorage.removeItem('practiceState');
  emit('practice-completed', {
    correctCount: correctCount.value,
    totalCount: questions.value.length,
    accuracy: accuracy.value,
    practiceTime: practiceTime.value
  });
};

const restartPractice = () => {
  showResult.value = false;
  showAnswers.value = false;
  questions.value = [];
  userAnswers.value = [];
  currentIndex.value = 0;
  userAnswer.value = '';
  correctCount.value = 0;
  practiceTime.value = 0;
  showAnswerForDrill.value = false; // 重置刷题模式答案显示状态
  isInitialDataLoaded.value = false; // 重置初始数据加载状态
  
  // 隐藏结果区域，重新开始练习
  // 清除保存的练习状态
  sessionStorage.removeItem('practiceState');
  
  // 重新开始练习
  startPractice();
};

const viewAnswers = () => {
  showAnswers.value = true;
};

// 返回设置页面
const returnToSettings = () => {
  console.log('returnToSettings 被调用');
  console.log('当前模块:', props.module);
  
  // 重置所有状态
  questions.value = [];
  userAnswers.value = [];
  currentIndex.value = 0;
  userAnswer.value = '';
  correctCount.value = 0;
  practiceTime.value = 0;
  showResult.value = false;
  showAnswers.value = false;
  showAnswerForDrill.value = false; // 重置刷题模式答案显示状态
  isInitialDataLoaded.value = false; // 重置初始数据加载状态
  
  // 重置练习表单设置
  practiceForm.count = 0;
  practiceForm.type = '';
  practiceForm.questionType = '';
  practiceForm.category = '';
  practiceForm.subCategory = '';
  practiceForm.module = '';
  practiceForm.mode = 'practice';
  
  // 停止计时
  stopTimer();
  // 清除保存的练习状态
  sessionStorage.removeItem('practiceState');
  sessionStorage.removeItem('practiceParams');
  
  // 根据当前模块返回到对应的设置页面
  // 使用浏览器后退功能
  console.log('准备返回上一页，模块:', props.module);
  
  // 直接使用浏览器后退
  router.back();
  console.log('已执行浏览器后退');
};



const getTypeText = (type: string) => {
  switch (type) {
    case 'single_choice': return '单选题';
    case 'multiple_choice': return '多选题';
    case 'true_false': return '判断题';
    case 'fill_blank': return '填空题';
    default: return '单选题';
  }
};

const parseOptions = (options: any) => {
  // 如果选项为空，返回空数组
  if (!options) return [];
  
  // 如果选项是字符串类型
  if (typeof options === 'string') {
    try {
      // 尝试解析JSON
      const parsedOptions = JSON.parse(options);
      // 确保解析后的结果是数组
      if (Array.isArray(parsedOptions)) {
        return parsedOptions;
      } else if (typeof parsedOptions === 'object') {
        // 如果是对象，转换为数组格式
        return Object.entries(parsedOptions).map(([key, value]) => ({ key, value }));
      }
    } catch (error) {
      // 如果JSON解析失败，尝试按行分割
      const lines = options.split('\n').filter((line: string) => line.trim());
      return lines.map((line: string, index: number) => {
        // 尝试解析每行为选项
        const match = line.match(/^([A-Z])[\.\s]?\s*(.+)$/);
        if (match) {
          // 如果行格式为 "A. 选项内容" 或 "A 选项内容"
          return { key: match[1], value: match[2].trim() };
        } else {
          // 否则使用索引生成选项键
          const key = String.fromCharCode(65 + index); // A, B, C, D...
          return { key, value: line.trim() };
        }
      });
    }
  }
  
  // 如果选项已经是数组，直接返回
  if (Array.isArray(options)) {
    return options;
  }
  
  // 如果选项是对象，转换为数组格式
  if (typeof options === 'object') {
    return Object.entries(options).map(([key, value]) => ({ key, value }));
  }
  
  // 默认返回空数组
  return [];
};

const isImageUrl = (url: any) => {
  if (typeof url !== 'string') return false;
  
  // 检查文件扩展名
  const imageExtensions = /\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i;
  
  // 检查是否是图片URL：包含图片扩展名、data:image/开头、或以/files/开头的本地路径
  return imageExtensions.test(url) || url.startsWith('data:image/') || url.startsWith('/files/');
};

const sanitizeHtml = (html: any) => {
  if (!html) return '';
  // 简单的HTML清理，实际项目中建议使用专门的库
  const cleanedHtml = html.replace(/<script[^>]*>.*?<\/script>/gi, '')
             .replace(/<iframe[^>]*>.*?<\/iframe>/gi, '')
             .replace(/javascript:/gi, '');
  
  // 调用修改题目内容图片和视频大小的函数
  return modifyQuestionContentImageSizeInHTML(cleanedHtml);
};

// 专门用于处理选项内容的函数
const sanitizeOptionHtml = (html: any) => {
  if (!html) return '';
  // 简单的HTML清理，实际项目中建议使用专门的库
  const cleanedHtml = html.replace(/<script[^>]*>.*?<\/script>/gi, '')
             .replace(/<iframe[^>]*>.*?<\/iframe>/gi, '')
             .replace(/javascript:/gi, '');
  
  // 调用修改选项图片和视频大小的函数
  return modifyOptionImageSizeInHTML(cleanedHtml);
};

const isCorrect = (correctAnswer: any, userAnswer: any) => {
  if (!userAnswer) return false;
  
  // 处理填空题
  if (currentQuestion.value && (currentQuestion.value.type === 'fill' || currentQuestion.value.type === 'fill_blank')) {
    // 填空题答案比较，忽略大小写和空格
    return String(userAnswer).trim().toLowerCase() === String(correctAnswer).trim().toLowerCase();
  }
  
  // 处理多选题
  if (Array.isArray(userAnswer)) {
    if (Array.isArray(correctAnswer)) {
      return userAnswer.length === correctAnswer.length && 
             userAnswer.every(ans => correctAnswer.includes(ans));
    } else {
      return userAnswer.length === 1 && userAnswer[0] === correctAnswer;
    }
  }
  
  // 处理单选题和判断题
  if (Array.isArray(correctAnswer)) {
    return correctAnswer.includes(userAnswer);
  }
  
  return String(userAnswer).toLowerCase() === String(correctAnswer).toLowerCase();
};

const formatAnswer = (answer: any) => {
  if (Array.isArray(answer)) {
    return answer.join(', ');
  }
  if (answer === 'true') return '正确';
  if (answer === 'false') return '错误';
  // 如果是填空题且答案不为空，直接返回答案
  if (answer && currentQuestion.value && (currentQuestion.value.type === 'fill' || currentQuestion.value.type === 'fill_blank')) {
    return answer;
  }
  return answer || '';
};

// AI答案生成方法
const generateAIAnswer = async () => {
  console.log('开始执行generateAIAnswer函数');
  if (!currentQuestion.value) {
    console.log('当前题目为空，无法生成AI解析');
    return;
  }
  
  aiLoading.value = true;
  showAIAnswer.value = true;
  console.log('已设置aiLoading为true，showAIAnswer为true');
  
  try {
    // 构造发送给AI的消息
    let message = `请为以下题目提供解析:\n\n题目: ${currentQuestion.value.content}\n`;
    
    // 如果有选项，添加选项信息
    if (currentQuestion.value.options) {
      const options = parseOptions(currentQuestion.value.options);
      message += '\n选项:\n';
      options.forEach((option: any) => {
        message += `${option.key}. ${option.value}\n`;
      });
    }
    
    message += '\n请提供详细的解题思路和解析，要求：\n1. 仅基于题目内容和选项进行分析，不要考虑用户选择的答案\n2. 提取核心要点，内容简洁明了\n3. 不超过200字\n4. 必须严格按照以下格式输出：\n【解析】[解析内容]\n【答案】[正确选项字母]';
    
    console.log('准备调用AI接口，消息内容:', message);
    
    // 调用AI接口
    const requestData = {
      message: message,
      modelType: 'aliyun', // 使用阿里云AI
      aliyunModel: 'qwen-plus' // 使用qwen-plus模型
    };
    
    const response: any = await sendAIMessage(requestData);
    console.log('AI接口返回结果:', response);
    
    if (response.code === 200) {
      // 提取核心内容，限制长度
      let aiContent = response.data || 'AI未能生成解析，请稍后重试';
      // 如果内容过长，提取核心要点
      if (aiContent.length > 300) {
        // 简单的截取方式，实际项目中可以使用更智能的摘要算法
        aiContent = aiContent.substring(0, 300) + '...';
      }
      aiAnswer.value = aiContent;
      // 将AI解析内容存储到缓存中
      const currentQuestionId = currentQuestion.value?.id || currentQuestion.value?.questionId;
      if (currentQuestionId) {
        aiAnswerCache.value[currentQuestionId] = aiContent;
      }
      console.log('已设置AI解析内容:', aiContent);
    } else {
      aiAnswer.value = 'AI解析生成失败，请稍后重试';
      console.log('AI解析生成失败:', response.message);
    }
  } catch (error) {
    console.error('AI解析生成失败:', error);
    aiAnswer.value = 'AI解析生成失败，请稍后重试';
  } finally {
    aiLoading.value = false;
    console.log('已设置aiLoading为false');
  }
};

const getResultMessage = (accuracy: number) => {
  if (accuracy >= 90) return '🎉 优秀！继续保持这种学习状态！';
  if (accuracy >= 80) return '👍 良好！再接再厉，争取更好成绩！';
  if (accuracy >= 70) return '💪 不错！继续努力，还有提升空间！';
  if (accuracy >= 60) return '📚 及格！需要加强练习，巩固知识点！';
  return '🔥 需要努力！建议重新学习相关知识点！';
};

// 添加应用AI答案到数据库的方法
const applyAIAnswerToDatabase = async () => {
  console.log('开始执行applyAIAnswerToDatabase函数');
  console.log('当前题目:', currentQuestion.value);
  console.log('AI答案:', aiAnswer.value);
  
  if (!currentQuestion.value || !aiAnswer.value) {
    console.log('缺少必要信息，无法应用AI答案到数据库');
    return;
  }
  
  applyingAI.value = true;
  
  try {
    // 从AI解析中提取正确答案（使用固定格式）
    let correctAnswer = currentQuestion.value.correctAnswer; // 默认使用原始答案
    
    // 使用固定格式提取答案：【答案】X
    const answerMatch = aiAnswer.value.match(/【答案】([A-D])/);
    if (answerMatch && answerMatch[1]) {
      correctAnswer = answerMatch[1];
      console.log('从AI解析中提取的正确答案:', correctAnswer);
    }
    
    // 构造更新数据
    const updateData = {
      questionId: currentQuestion.value.id || currentQuestion.value.questionId,
      explanation: aiAnswer.value,
      correctAnswer: correctAnswer
    };
    
    console.log('准备发送更新请求，数据:', updateData);
    console.log('API路径:', `/api/${props.module}/questions/${updateData.questionId}/explanation`);
    
    // 调用更新题目的API接口
    // 这里假设有一个更新题目的API接口，你需要根据实际的API接口进行调整
    const response: any = await request.put(`/api/${props.module}/questions/${updateData.questionId}/explanation`, updateData);
    
    console.log('API返回结果:', response);
    
    if (response.code === 200) {
      ElMessage.success('AI答案已成功应用到数据库');
      // 更新当前题目中的解析内容
      if (currentQuestion.value) {
        currentQuestion.value.explanation = aiAnswer.value;
        currentQuestion.value.analysis = aiAnswer.value;
        // 如果正确答案被更新，也更新当前题目中的正确答案
        if (correctAnswer !== currentQuestion.value.correctAnswer) {
          currentQuestion.value.correctAnswer = correctAnswer;
        }
      }
    } else {
      ElMessage.error('应用AI答案失败: ' + (response.message || '未知错误'));
    }
  } catch (error) {
    console.error('应用AI答案失败:', error);
    ElMessage.error('应用AI答案失败，请稍后重试');
  } finally {
    applyingAI.value = false;
  }
};

// 生命周期
onMounted(() => {
  // 用户进度功能已移除
  // 检查是否有保存的练习参数
  const savedPracticeParams = sessionStorage.getItem('practiceParams');
  if (savedPracticeParams) {
    try {
      const params = JSON.parse(savedPracticeParams);
      // 使用保存的参数开始练习
      // 修正参数结构：直接使用params而不是params.params
      startPractice(params);
      // 清除已使用的参数
      sessionStorage.removeItem('practiceParams');
    } catch (e) {
      console.error('Failed to restore practice params:', e);
      // 如果恢复失败，清除保存的参数
      sessionStorage.removeItem('practiceParams');
    }
  }
  // 注意：不再使用默认参数自动开始练习
  
  // 检查是否有保存的练习状态
  const savedPracticeState = sessionStorage.getItem('practiceState');
  if (savedPracticeState) {
    try {
      const state = JSON.parse(savedPracticeState);
      // 恢复练习状态
      questions.value = state.questions || [];
      currentIndex.value = state.currentIndex || 0;
      userAnswers.value = state.userAnswers || new Array(state.questions?.length || 0).fill('');
      practiceTime.value = state.practiceTime || 0;
      // 恢复刷题模式相关状态
      if (state.practiceMode === 'drill') {
        showAnswerForDrill.value = true; // 在刷题模式下默认显示答案和解析
      } else {
        showAnswerForDrill.value = false;
      }
      // 更新practiceForm的模式设置
      practiceForm.mode = state.practiceMode || 'practice';
      
      
      // 如果有题目且当前索引有效，加载当前题目的答案
      if (questions.value.length > 0 && currentIndex.value < questions.value.length) {
        loadAnswer();
      }
      
      // 如果有计时且计时大于0，重新开始计时
      if (props.showTimer && practiceTime.value > 0) {
        startTimer();
      }
      
      // 标记已加载初始数据
      isInitialDataLoaded.value = true;
    } catch (e) {
      console.error('Failed to restore practice state:', e);
      // 如果恢复失败，清除保存的状态
      sessionStorage.removeItem('practiceState');
    }
  }
});

onUnmounted(() => {
  stopTimer();
});

// 监听答案变化
watch(userAnswer, (newAnswer) => {
  // 只有当用户选择了答案时才保存并更新进度
  if (newAnswer && newAnswer !== '') {
    // 做题模式下直接保存答案
    if (practiceForm.mode === 'practice') {
      saveCurrentAnswer();
    }
    // 刷题模式下，选择答案后立即显示答案和解析
    if (practiceForm.mode === 'drill') {
      console.log('刷题模式下选择答案，准备显示AI解析区域');
      showAnswerForDrill.value = true;
      // 在刷题模式下也保存答案到userAnswers数组中
      if (currentIndex.value >= 0 && currentIndex.value < userAnswers.value.length) {
        userAnswers.value[currentIndex.value] = newAnswer as never;
        // 保存练习状态到 sessionStorage
        savePracticeState();
      }
      // 自动显示AI解析区域
      showAIAnswer.value = true;
      console.log('已设置showAIAnswer为true');
      // 检查题目是否有原有解析内容
      const hasOriginalExplanation = currentQuestion.value?.explanation || currentQuestion.value?.analysis;
      // 只有在没有原有解析内容时才自动加载AI解析
      if (!aiAnswer.value && !aiLoading.value && !hasOriginalExplanation) {
        console.log('开始生成AI解析');
        generateAIAnswer();
      }
    }
    // 可以在这里添加进度更新逻辑
  }
});

// 监听刷题模式下userAnswers数组的变化，确保userAnswer.value与userAnswers.value[currentIndex.value]同步
watch([userAnswers, currentIndex], () => {
  if (practiceForm.mode === 'drill' && currentIndex.value >= 0 && currentIndex.value < userAnswers.value.length) {
    // 确保userAnswer.value与当前题目的答案同步
    const currentAnswer = userAnswers.value[currentIndex.value] || '';
    if (userAnswer.value !== currentAnswer) {
      userAnswer.value = currentAnswer;
    }
    // 如果当前题目已有答案，在刷题模式下应该显示答案和解析
    if (currentAnswer) {
      showAnswerForDrill.value = true;
      // 同时显示AI解析区域
      showAIAnswer.value = true;
    }
  }
});
</script>

<style scoped>
/* 全局重置和优化 */
* {
  box-sizing: border-box;
}

/* 整体布局 - 苹果风格 */
.unified-practice {
  width: 100%;
  max-width: min(1400px, 95vw);
  margin: 0 auto;
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
  min-height: auto;
  height: auto;
  border-radius: 24px;
  position: relative;
  overflow: visible;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
}

.unified-practice::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 15% 85%, rgba(255, 255, 255, 0.6) 0%, transparent 40%),
    radial-gradient(circle at 85% 15%, rgba(240, 245, 255, 0.4) 0%, transparent 40%),
    radial-gradient(circle at 45% 45%, rgba(255, 255, 255, 0.3) 0%, transparent 40%);
  pointer-events: none;
  border-radius: 24px;
}

/* 头部样式 - 苹果风格 */
.practice-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 30px 24px;
  background: rgba(255, 255, 255, 0.85);
  border-radius: 20px;
  color: #333;
  position: relative;
  z-index: 1;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.5);
  width: 100%;
  box-sizing: border-box;
  flex-shrink: 0;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.header-top {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 24px;
}

.return-home-btn {
  background: rgba(0, 0, 0, 0.05) !important;
  border: 1px solid rgba(0, 0, 0, 0.1) !important;
  color: #333 !important;
  backdrop-filter: blur(10px);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  border-radius: 12px;
  font-weight: 500;
  padding: 8px 16px;
}

.return-home-btn:hover {
  background: rgba(0, 0, 0, 0.1) !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.practice-header h1 {
  font-size: 32px;
  margin-bottom: 12px;
  font-weight: 600;
  color: #1d1d1f;
  letter-spacing: -0.5px;
}

.practice-header p {
  font-size: 16px;
  margin-bottom: 20px;
  color: #86868b;
  font-weight: 400;
}

/* 进度展示 */
.practice-progress {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 25px;
  gap: 40px;
}

.progress-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  text-align: center;
  background: rgba(255, 255, 255, 0.2);
  padding: 20px 25px;
  border-radius: 15px;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.stat-item:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-3px);
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  display: block;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.progress-value {
  font-size: 28px;
  font-weight: 700;
  display: block;
  margin-bottom: 5px;
}

.progress-label {
  font-size: 12px;
  opacity: 0.8;
}

/* 练习内容 - 苹果风格 */
.practice-content {
  position: relative;
  z-index: 1;
  width: 100%;
  box-sizing: border-box;
}

.practice-settings {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
  width: 100%;
  box-sizing: border-box;
}

.settings-card,
.tips-card {
  border-radius: 18px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.6);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
}

.settings-card:hover,
.tips-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 18px;
  font-weight: 600;
  color: #1d1d1f;
  padding: 20px 24px;
}

.question-info {
  display: flex;
  align-items: center;
  flex: 1;
  margin: 0 16px;
  min-width: 0;
}

.question-progress {
  margin-left: 16px;
  flex: 1;
  max-width: 350px;
  min-width: 200px;
}

/* 已移除，使用新的布局结构 */

.tips-content p {
  margin: 16px 0;
  color: #86868b;
  line-height: 1.6;
  padding-left: 24px;
  position: relative;
  font-size: 15px;
}

.tips-content p::before {
  content: '•';
  position: absolute;
  left: 12px;
  color: #0071e3;
  font-weight: bold;
  top: 2px;
}

.start-button {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 500;
  background: #0071e3;
  border: none;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  color: white;
  letter-spacing: 0.2px;
}

.start-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 20px rgba(0, 113, 227, 0.3);
  background: #0077ed;
}

/* 题目区域 - 苹果风格 */
.question-area {
  margin-top: 24px;
}

.question-container {
  display: grid;
  grid-template-columns: 7fr 0.5fr;
  gap: 16px;
  width: 100%;
  box-sizing: border-box;
}

.question-card {
  border-radius: 18px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.6);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
}

.question-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.08);
}

.question-card .el-card__header {
  background: rgba(255, 255, 255, 0.8);
  color: #1d1d1f;
  padding: 16px 30px;
  position: relative;
  overflow: hidden;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

/* 已移至.card-header中定义 */

.return-btn {
  background: transparent; /* 透明背景 */
  border: none; /* 无边框 */
  color: #0071e3; /* 蓝色文字 */
  border-radius: 6px;
  padding: 4px 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 4px;
}

.return-btn:hover {
  background: rgba(0, 113, 227, 0.1); /* 悬停时轻微背景 */
  transform: translateY(-1px);
}

.question-number {
  font-weight: 600;
  color: #1d1d1f;
  font-size: 16px;
  white-space: nowrap;
}

.question-tags {
  display: flex;
  align-items: center;
  gap: 12px;
  justify-content: flex-end;
  flex: 1;
}

.tag-content {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
}

/* 题目内容 - 苹果风格 */
.question-content {
  padding: 6px 30px 24px 30px;
  width: 100%;
  box-sizing: border-box;
}

.question-content h3 {
  margin-bottom: 16px;
  font-size: 17px;
  line-height: 1.6;
  color: #1d1d1f;
  padding: 0;
  background: transparent;
  border-radius: 0;
  box-shadow: none;
  font-weight: 500;
}

.question-index {
  color: #0071e3;
  font-weight: 600;
  margin-right: 10px;
  vertical-align: top;
  display: inline-block;
}

/* 选项样式 - 苹果风格 */
.options {
  margin: 24px 0;
  padding: 0;
  width: 100%;
  box-sizing: border-box;
}

.option-item {
  margin: 0 0 16px 0;
  width: 100%;
  border-radius: 14px;
  padding: 18px 22px;
  background: rgba(255, 255, 255, 0.7);
  border: 1px solid rgba(0, 0, 0, 0.08);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  cursor: pointer;
  position: relative;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
}

.option-item:hover {
  border-color: rgba(0, 113, 227, 0.3);
  background: rgba(255, 255, 255, 0.9);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 113, 227, 0.1);
}

.option-item.is-checked {
  border-color: #0071e3;
  background: rgba(0, 113, 227, 0.05);
  box-shadow: 0 2px 8px rgba(0, 113, 227, 0.15);
}

.option-content {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  line-height: 1.5;
}

.option-key {
  font-weight: 600;
  color: #0071e3;
  font-size: 14px;
  min-width: 26px;
  height: 26px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 113, 227, 0.1);
  border-radius: 50%;
  flex-shrink: 0;
}

.option-value {
  flex: 1;
  font-size: 16px;
  color: #1d1d1f;
  line-height: 1.5;
  font-weight: 400;
}

.option-image {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

/* 填空题样式 - 苹果风格 */
.fill-input {
  width: 100%;
  margin: 24px 0;
}

.fill-input .el-textarea__inner {
  border-radius: 14px;
  padding: 18px 22px;
  font-size: 16px;
  line-height: 1.5;
  border: 1px solid rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
}

.fill-input .el-textarea__inner:focus {
  border-color: #0071e3;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0 0 0 3px rgba(0, 113, 227, 0.1);
}

/* 判断题特殊样式 - 苹果风格 */
.options .el-radio {
  margin-right: 0;
  margin-bottom: 16px;
  width: 100%;
}

.options .el-radio .el-radio__label {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 16px;
  font-weight: 400;
  padding: 18px 22px;
  border-radius: 14px;
  background: rgba(255, 255, 255, 0.7);
  border: 1px solid rgba(0, 0, 0, 0.08);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  width: 100%;
  margin-left: 0;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
}

.options .el-radio.is-checked .el-radio__label {
  background: rgba(0, 113, 227, 0.05);
  border-color: #0071e3;
  color: #0071e3;
}

.options .el-radio:hover .el-radio__label {
  border-color: rgba(0, 113, 227, 0.3);
  background: rgba(255, 255, 255, 0.9);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 113, 227, 0.1);
}

/* 题目操作按钮 - 苹果风格 */
.question-actions {
  margin-top: 24px;
  padding: 20px 24px;
  background: rgba(255, 255, 255, 0.6);
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  width: 100%;
  box-sizing: border-box;
  flex-wrap: wrap;
}

.nav-button {
  min-width: 110px;
  height: 44px;
  border-radius: 12px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  border: 1px solid rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.8);
  color: #1d1d1f;
}

.nav-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 1);
}

.submit-button {
  min-width: 130px;
  height: 44px;
  border-radius: 12px;
  font-weight: 500;
  background: #34c759;
  border: none;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  color: white;
}

.submit-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(52, 199, 89, 0.3);
  background: #2db44f;
}

/* 侧边栏 - 苹果风格 */
.sidebar-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 计时器卡片 - 苹果风格 */
.timer-card {
  border-radius: 18px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.6);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.05);
}

.timer-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 28px rgba(0, 0, 0, 0.07);
}

.timer-content {
  text-align: center;
  padding: 24px;
}

.timer-display {
  font-size: 36px;
  font-weight: 600;
  color: #0071e3;
  margin-bottom: 12px;
  font-variant-numeric: tabular-nums;
}

.timer-tip {
  color: #86868b;
  font-size: 14px;
  font-weight: 400;
}

/* 答题卡 - 苹果风格 */
.answer-card-panel {
  border-radius: 18px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.6);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.05);
}

.answer-card-panel:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 28px rgba(0, 0, 0, 0.07);
}

.answer-card-content {
  padding: 20px;
}

.answer-card-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  margin-bottom: 20px;
}

.answer-card-item {
  width: 100%;
  aspect-ratio: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  border: 1px solid rgba(0, 0, 0, 0.08);
  position: relative;
  overflow: hidden;
  font-size: 14px;
  background: rgba(255, 255, 255, 0.7);
  color: #86868b;
}

.answer-card-item:hover {
  background: rgba(255, 255, 255, 0.9);
}


.answer-card-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.9);
}

.answer-card-item.current {
  background: #0071e3;
  color: white;
  border-color: #0071e3;
  box-shadow: 0 4px 12px rgba(0, 113, 227, 0.2);
}

.answer-card-item.answered,
.answer-card-item.correct {
  background: #34c759;
  color: white;
  border-color: #34c759;
}

.answer-card-item.incorrect {
  background: #ff3b30;
  color: white;
  border-color: #ff3b30;
}

.answer-card-item.unanswered {
  background: rgba(255, 255, 255, 0.7);
  color: #86868b;
  border-color: rgba(0, 0, 0, 0.08);
}

.answer-card-stats {
  display: flex;
  justify-content: space-between;
  padding-top: 16px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

.answer-card-stats .stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #86868b;
  font-weight: 400;
  white-space: nowrap;
  min-width: 0; /* 允许子元素收缩 */
}

.answer-card-stats .stat-item span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.stat-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  flex-shrink: 0; /* 防止颜色指示器被压缩 */
}

.stat-color.answered {
  background: #34c759;
}

.stat-color.incorrect {
  background: #ff3b30;
}

.stat-color.unanswered {
  background-color: #f5f5f7;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

/* 答题卡分页控件样式 */
.answer-card-pagination {
  display: flex;
  justify-content: center;
  margin: 16px 0;
}

.answer-card-pagination :deep(.el-pagination) {
  display: flex;
  align-items: center;
  justify-content: center;
}

.answer-card-pagination :deep(.el-pagination__pager) {
  display: flex;
  align-items: center;
}

.answer-card-pagination :deep(.el-pager li) {
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  border-radius: 8px;
  margin: 0 2px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.answer-card-pagination :deep(.el-pager li:hover) {
  color: #0071e3;
  background-color: rgba(0, 113, 227, 0.1);
}

.answer-card-pagination :deep(.el-pager li.active) {
  background-color: #0071e3;
  color: white;
}

.answer-card-pagination :deep(.el-pagination__jump) {
  margin-left: 16px;
  font-size: 14px;
  color: #86868b;
}

.answer-card-pagination :deep(.el-pagination__editor) {
  width: 50px;
  margin: 0 8px;
}

  /* 结果区域 - 苹果风格 */
  .result-area {
    margin-top: 30px;
  }

  .result-card {
    border-radius: 18px;
    overflow: hidden;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(20px);
    border: 1px solid rgba(255, 255, 255, 0.6);
    transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
  }

  .result-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 32px rgba(0, 0, 0, 0.08);
  }

  .result-card .el-card__header {
    background: rgba(255, 255, 255, 0.8);
    color: #1d1d1f;
    padding: 24px 30px;
    position: relative;
    overflow: hidden;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  }

  .practice-time {
    font-size: 16px;
    color: #86868b;
    font-weight: 400;
  }

  .result-content {
    padding: 40px;
    text-align: center;
  }

  .result-summary {
    margin-bottom: 40px;
  }

  .result-title {
    font-size: 22px;
    margin-bottom: 16px;
    color: #1d1d1f;
    font-weight: 600;
  }

  .result-message {
    font-size: 17px;
    color: #86868b;
    line-height: 1.6;
  }

  .result-stats {
    margin: 40px 0;
  }

  .result-item {
    text-align: center;
    padding: 24px 20px;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 14px;
    transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    border: 1px solid rgba(0, 0, 0, 0.05);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
  }

  .result-item:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    background: rgba(255, 255, 255, 0.8);
  }

  .result-icon {
    font-size: 28px;
    margin-bottom: 16px;
    color: #0071e3;
  }

  .result-icon.correct {
    color: #34c759;
  }

  .result-icon.error {
    color: #ff3b30;
  }

  .result-item h3 {
    font-size: 15px;
    margin-bottom: 12px;
    color: #86868b;
    font-weight: 500;
  }

  .result-number {
    font-size: 32px;
    font-weight: 600;
    margin: 0;
    color: #1d1d1f;
  }

  .result-number.correct {
    color: #34c759;
  }

  .result-number.error {
    color: #ff3b30;
  }

  .accuracy-chart {
    margin: 40px 0;
    display: flex;
    justify-content: center;
  }

  .result-actions {
    display: flex;
    justify-content: center;
    gap: 16px;
    margin-top: 40px;
  }

  .action-button {
    min-width: 130px;
    height: 44px;
    border-radius: 12px;
    font-weight: 500;
    transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    display: flex;
    align-items: center;
    gap: 8px;
    background: rgba(255, 255, 255, 0.8);
    border: 1px solid rgba(0, 0, 0, 0.1);
    color: #1d1d1f;
  }

  .action-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    background: rgba(255, 255, 255, 1);
  }

  /* 答案解析 - 苹果风格 */
  .answer-review {
    margin-top: 30px;
  }

  .answer-card {
    border-radius: 18px;
    overflow: hidden;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(20px);
    border: 1px solid rgba(255, 255, 255, 0.6);
    transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
  }

  .answer-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 32px rgba(0, 0, 0, 0.08);
  }

  .answer-card .el-card__header {
    background: rgba(255, 255, 255, 0.8);
    color: #1d1d1f;
    padding: 24px 30px;
    position: relative;
    overflow: hidden;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  }

  .answer-list {
    padding: 24px;
    max-height: none;
    overflow-y: visible;
  }

  .answer-item {
    margin-bottom: 24px;
    padding: 24px;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 14px;
    transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
  }

  .answer-item:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  }

  .answer-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    gap: 16px;
  }

  .answer-header h4 {
    flex: 1;
    font-size: 17px;
    line-height: 1.6;
    color: #1d1d1f;
    margin: 0;
    font-weight: 500;
  }

  .answer-tag {
    flex-shrink: 0;
    font-weight: 500;
  }

  .answer-details {
    margin-top: 20px;
  }

  .answer-details p {
    margin: 16px 0;
    font-size: 16px;
    line-height: 1.6;
    color: #1d1d1f;
  }

  .correct-answer {
    color: #34c759;
    font-weight: 600;
    padding: 4px 8px;
    background: rgba(52, 199, 89, 0.1);
    border-radius: 6px;
  }

  .user-answer-correct {
    color: #34c759;
    font-weight: 600;
    padding: 4px 8px;
    background: rgba(52, 199, 89, 0.1);
    border-radius: 6px;
  }

  .user-answer-wrong {
    color: #ff3b30;
    font-weight: 600;
    padding: 4px 8px;
    background: rgba(255, 59, 48, 0.1);
    border-radius: 6px;
  }

  .answer-explanation {
    margin-top: 20px;
    padding: 20px;
    background: rgba(0, 113, 227, 0.05);
    border-radius: 10px;
    line-height: 1.6;
    color: #1d1d1f;
  }

  .answer-explanation strong {
    color: #0071e3;
    font-weight: 600;
  }

/* 刷题模式答案显示样式 */
.drill-answer-section {
  margin-top: 20px;
  padding: 20px;
  background: rgba(52, 199, 89, 0.1);
  border-radius: 10px;
  border: 1px solid rgba(52, 199, 89, 0.2);
}

.drill-answer-section .answer-explanation {
  background: transparent;
  padding: 0;
  margin-bottom: 20px;
}

.drill-answer-section .explanation-content {
  margin-top: 10px;
}

/* AI答案部分样式 */
.ai-answer-section {
  margin-top: 20px;
  padding: 20px;
  background: rgba(0, 113, 227, 0.1);
  border-radius: 10px;
  border: 1px solid rgba(0, 113, 227, 0.2);
}

.ai-loading {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #0071e3;
  font-weight: 500;
}

.ai-answer-content {
  margin-top: 10px;
  line-height: 1.6;
}

.ai-answer-content strong {
  color: #0071e3;
  font-weight: 600;
}

.ai-content {
  margin-top: 10px;
  line-height: 1.6;
  color: #1d1d1f;
  font-size: 15px;
  white-space: pre-wrap;
}

.ai-content :deep(p) {
  margin: 10px 0;
  line-height: 1.6;
}

.ai-content :deep(strong) {
  font-weight: 600;
  color: #0071e3;
}

.ai-content :deep(em) {
  font-style: italic;
}

.ai-content :deep(ul), .ai-content :deep(ol) {
  margin: 10px 0;
  padding-left: 20px;
}

.ai-content :deep(li) {
  margin: 5px 0;
}

.ai-content :deep(h1), .ai-content :deep(h2), .ai-content :deep(h3) {
  margin: 15px 0 10px 0;
  font-weight: 600;
}

.ai-content :deep(h1) {
  font-size: 1.5em;
}

.ai-content :deep(h2) {
  font-size: 1.3em;
}

.ai-content :deep(h3) {
  font-size: 1.1em;
}

.ai-content :deep(pre) {
  background: rgba(0, 0, 0, 0.05);
  padding: 10px;
  border-radius: 5px;
  overflow-x: auto;
  margin: 10px 0;
}

.ai-content :deep(code) {
  background: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.generate-ai-btn {
  background: #0071e3;
  border: none;
  color: white;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 14px;
  transition: all 0.3s ease;
  margin-right: 10px;
}

.generate-ai-btn:hover {
  background: #0077ed;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 113, 227, 0.2);
}

.apply-ai-btn {
  background: #34c759;
  border: none;
  color: white;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.apply-ai-btn:hover {
  background: #2db44f;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(52, 199, 89, 0.2);
}

/* 响应式设计 - 苹果风格 */

  /* 响应式设计 - 苹果风格 */
  @media (min-width: 1920px) {
    .unified-practice {
      max-width: 1600px;
      margin: 0 auto;
      padding: 24px;
    }
    
    .practice-content {
      padding: 0 24px;
    }
    
    .question-content h3 {
      font-size: 18px;
    }
    
    .option-content {
      font-size: 16px;
    }
  }

  @media (max-width: 1400px) {
    .unified-practice {
      padding: 20px;
      min-height: auto;
    }
    
    .practice-header {
      padding: 24px;
    }
    
    .answer-card-stats .stat-item {
      white-space: nowrap;
    }
    
    .answer-card-stats .stat-item span {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .stat-color {
      flex-shrink: 0;
    }
  }

  @media (max-width: 1200px) {
    .unified-practice {
      padding: 16px;
      border-radius: 20px;
    }
    
    .question-container {
      grid-template-columns: 1fr;
      gap: 20px;
    }

    .sidebar-container {
      grid-template-columns: 1fr 1fr;
      display: grid;
      gap: 16px;
    }
    
    .practice-settings {
      gap: 20px;
    }
    
    .el-form {
      padding: 0 16px;
    }
    
    .answer-card-stats .stat-item {
      white-space: nowrap;
    }
    
    .answer-card-stats .stat-item span {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .stat-color {
      flex-shrink: 0;
    }
  }

  @media (max-width: 992px) {
    .unified-practice {
      padding: 16px;
      border-radius: 18px;
      min-height: auto;
    }

    .practice-header {
      padding: 24px 20px;
    }

    .practice-header h1 {
      font-size: 28px;
    }
    
    .practice-header p {
      font-size: 16px;
    }

    .practice-settings {
      grid-template-columns: 1fr;
      gap: 20px;
    }
    
    .question-content {
      padding: 24px 20px;
    }
    
    .question-content h3 {
      font-size: 17px;
      padding: 20px;
    }
    
    .option-item {
      padding: 18px 22px;
    }
    
    .result-stats {
      gap: 16px;
    }
    
    .answer-card-stats .stat-item {
      white-space: nowrap;
    }
    
    .answer-card-stats .stat-item span {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .stat-color {
      flex-shrink: 0;
    }
  }

  @media (max-width: 768px) {
    .unified-practice {
      padding: 14px;
      border-radius: 16px;
      min-height: auto;
    }

    .practice-header {
      padding: 20px 16px;
    }

    .practice-header h1 {
      font-size: 26px;
      margin-bottom: 12px;
    }
    
    .practice-header p {
      font-size: 15px;
    }
    
    .header-top {
      margin-bottom: 16px;
    }
    
    .return-home-btn {
      padding: 8px 16px;
      font-size: 14px;
    }

    .practice-settings {
      grid-template-columns: 1fr;
      gap: 16px;
    }
    
    .settings-card,
    .tips-card {
      border-radius: 16px;
    }
    
    .el-form {
      padding: 0;
    }
    
    .el-form-item {
      margin-bottom: 16px;
    }
    
    .el-form-item__label {
      font-size: 15px;
      line-height: 1.4;
    }

    .sidebar-container {
      grid-template-columns: 1fr;
      gap: 16px;
    }
    
    .question-card {
      border-radius: 16px;
    }
    
    .question-content {
      padding: 20px 16px;
    }
    
    .question-content h3 {
      font-size: 16px;
      padding: 18px 16px;
      margin-bottom: 20px;
    }
    
    .question-progress {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
    }
    
    .question-tags {
      align-self: flex-end;
    }
    
    .option-item {
      padding: 16px 20px;
      margin-bottom: 12px;
    }
    
    .option-content {
      gap: 14px;
      font-size: 15px;
    }
    
    .option-key {
      min-width: 24px;
      height: 24px;
      font-size: 13px;
    }

    .answer-card-grid {
      grid-template-columns: repeat(5, 1fr);
      gap: 8px;
    }
    
    .answer-card-item {
      width: 32px;
      height: 32px;
      font-size: 13px;
    }

    .result-actions {
      flex-direction: column;
      align-items: center;
      gap: 12px;
    }

    .action-button {
      width: 100%;
      max-width: 280px;
      height: 42px;
      font-size: 15px;
    }

    .question-actions {
      flex-direction: column;
      gap: 12px;
      margin-top: 24px;
    }

    .nav-button,
    .submit-button {
      width: 100%;
      height: 42px;
      min-height: 42px;
      font-size: 15px;
    }
    
    .result-stats {
      gap: 12px;
    }
    
    .result-item h3 {
      font-size: 14px;
    }
    
    .result-number {
      font-size: 28px;
    }
    
    .timer-card,
    .answer-card-panel {
      border-radius: 16px;
    }
    
    .timer-content {
      padding: 20px;
    }
    
    .timer-display {
      font-size: 32px;
    }
    
    .answer-list {
      padding: 20px 16px;
    }
    
    .answer-item {
      padding: 20px 16px;
      margin-bottom: 20px;
    }
    
    .answer-card-stats .stat-item {
      white-space: nowrap;
    }
    
    .answer-card-stats .stat-item span {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .stat-color {
      flex-shrink: 0;
    }
  }

  @media (max-width: 576px) {
    .unified-practice {
      padding: 12px;
      margin: 6px;
      min-height: auto;
    }
    
    .practice-header {
      padding: 16px 14px;
    }
    
    .practice-header h1 {
      font-size: 24px;
    }
    
    .practice-header p {
      font-size: 14px;
    }
    
    .card-header {
      font-size: 16px;
    }
    
    .el-form-item__label {
      font-size: 14px;
      line-height: 1.3;
    }
    
    .question-content {
      padding: 16px 14px;
    }
    
    .question-content h3 {
      font-size: 15px;
      padding: 16px 14px;
    }
    
    .option-item {
      padding: 14px 16px;
      margin-bottom: 10px;
    }
    
    .option-content {
      gap: 12px;
      font-size: 14px;
    }
    
    .option-key {
      min-width: 22px;
      height: 22px;
      font-size: 12px;
    }
    
    .answer-card-grid {
      grid-template-columns: repeat(4, 1fr);
      gap: 6px;
    }
    
    .answer-card-item {
      width: 28px;
      height: 28px;
      font-size: 12px;
    }
    
    .result-stats .el-col {
      margin-bottom: 15px;
    }
    
    .result-item {
      padding: 15px 12px;
    }
    
    .result-item h3 {
      font-size: 13px;
    }
    
    .result-number {
      font-size: 24px;
    }
    
    .action-button {
      height: 40px;
      font-size: 14px;
      max-width: 100%;
    }
    
    .nav-button,
    .submit-button {
      height: 40px;
      min-height: 40px;
      font-size: 14px;
    }
    
    .timer-display {
      font-size: 28px;
    }
    
    .answer-header {
      flex-direction: column;
      gap: 12px;
    }

    .answer-tag {
      align-self: flex-start;
    }
    
    .answer-header h4 {
      font-size: 15px;
    }
    
    .answer-details p {
      font-size: 14px;
    }
    
    .answer-explanation {
      padding: 16px;
      font-size: 14px;
    }
    
    .answer-card-stats .stat-item {
      white-space: nowrap;
    }
    
    .answer-card-stats .stat-item span {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .stat-color {
      flex-shrink: 0;
    }
  }

  @media (max-width: 480px) {
    .unified-practice {
      padding: 10px;
      margin: 4px;
    }
    
    .practice-progress {
      flex-direction: column;
      gap: 16px;
    }

    .progress-stats {
      margin-left: 0;
      justify-content: center;
      flex-wrap: wrap;
      gap: 16px;
    }
    
    .stat-item {
      padding: 16px 20px;
      min-width: 8rem;
    }
    
    .stat-value {
      font-size: 24px;
    }
    
    .answer-card-grid {
      grid-template-columns: repeat(3, 1fr);
    }
    
    .answer-card-item {
      width: 26px;
      height: 26px;
      font-size: 11px;
    }
    
    .question-number {
      font-size: 14px;
    }
    
    .fill-input {
      font-size: 14px;
    }
    
    .tips-content p {
      font-size: 14px;
      padding-left: 16px;
    }
    
    .answer-card-stats .stat-item {
      white-space: nowrap;
    }
    
    .answer-card-stats .stat-item span {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .stat-color {
      flex-shrink: 0;
    }
  }
  
  /* 横屏适配 - 苹果风格 */
  @media (max-height: 600px) and (orientation: landscape) {
    .unified-practice {
      padding: 12px 16px;
      min-height: auto;
    }
    
    .practice-header {
      padding: 16px;
    }
    
    .practice-header h1 {
      font-size: 24px;
      margin-bottom: 8px;
    }
    
    .question-content {
      padding: 16px;
    }
    
    .question-content h3 {
      padding: 14px 16px;
      margin-bottom: 16px;
    }
    
    .option-item {
      padding: 14px 16px;
      margin-bottom: 10px;
    }
    
    .question-actions {
      margin-top: 16px;
      padding: 16px;
    }
    
    .answer-list {
      max-height: none;
      padding: 16px;
    }
    
    .result-content {
      padding: 24px;
    }
  }
</style>
